在双向多对多关系中,我们必须指定一个关系维护端(owner side),可以通过 @ManyToMany 注释中指定 mappedBy 属性来标识其为关系维护端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| @Entity @Table(name = "t_item") public class Item { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name;
@ManyToMany @JoinTable(name = "item_category",joinColumns = { @JoinColumn(name = "item_id",referencedColumnName = "id")}, inverseJoinColumns = { @JoinColumn(name = "category_id",referencedColumnName = "id")}) private Set<Category> categories=new HashSet<Category>();
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set<Category> getCategories() { return categories; }
public void setCategories(Set<Category> categories) { this.categories = categories; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @Entity @Table(name = "t_category") public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name;
@ManyToMany(mappedBy = "categories") private Set<Item> items=new HashSet<Item>();
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Set<Item> getItems() { return items; }
public void setItems(Set<Item> items) { this.items = items; } }
|