Hibernate mapping, entity with many to many relationship table

时间:2017-08-05 11:25:40

标签: java hibernate mapping hibernate-mapping

I got a many to many relationship between two tables. I mapping this using the annotation @ManyToMany.

Table1 ---> Relational Table ---> Table 2

Using hibernate i don't have to create any entity for the relationship table so I have.

Entity 1(Table 1) ---> Entity 2(Table 2)

But my problem is that i have another table and i must do a relationship between this 3th table and the relation table between the previous and i don't have any entity for do the relation.

Table 3 ---> Relational Table

I mean this 3th table got a foreign key with the relational table that i used before...

How can i accomplishment this? Sorry for my english

Thanks

1 个答案:

答案 0 :(得分:0)

这是一个例子。 想象一下,我们有产品和类别 您有2个实体产品和类别

使用hibernate代码优先方法,实体将是这样的:

@Entity
@Table(name = "products")
public class Product implements Serializable {
private Long id;
....

@ManyToMany
@JoinTable(name = "categories_products",
joinColumns = @JoinColumn(name = "category_id",
referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "product_id",
referencedColumnName = "id"))
private Set<Category> categories;
...

这是代码的代码

public class Category {
private Long id;
private String name;
...
}

通过使用注释@JoinTable,将使用以下约束创建第三个表。它将具有category_id,它将指向Categories id和product_id,引用Products id。

相关问题