简体   繁体   English

@JoinTable联接三个表

[英]@JoinTable to join three tables

How can I use @JoinTable to join three tables? 如何使用@JoinTable三个表?

I have three tables: 我有三个表:

user:
id, name 

post:
id, date

company:
id, name

I want to create a new table with the following columns: 我想用以下几列创建一个新表:

user_id, post_id, company_id.

I used: 我用了:

@JoinTable(name = "new_table", joinColumns = @JoinColumn(name = "user_id"),
    inverseJoinColumns = @JoinColumn(name = "post_id"))

However, I am not sure how to add the third column. 但是,我不确定如何添加第三列。

You must not will use @JoinTable annotation. 您一定不能使用@JoinTable批注。 The @JoinTable annotation is used only to @ManyToMany relationship. @JoinTable批注仅用于@ManyToMany关系。

You need create a new Entity with three field, and each field must has the @ManyToOne and @JoinColumn annotation. 您需要使用三个字段创建一个新的Entity,每个字段必须具有@ManyToOne和@JoinColumn批注。

For Instance: 例如:

@Entity
@Table(name = "table_name")
class NewEntity {

    //Id and anothers fields

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    @ManyToOne
    @JoinColumn(name = "post_id")
    private Post post;

    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;

    //getters and setters       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM