1.对于@OneToMany和@ManyToOne来说是一样,两张表互相维护,加入mappedBy="",由被控方维护的表,增加外键即可。如果是没有增加上面类型,就会产生一个第三方表进行维护。
2.对于@ManyToMany注解来说,也是一样的,在这里需要注意一下,我们需要一个第三方表来维护多对多的关系,如果想要实现没有第三方表,可以采用两次多对一的关系结构。
3.实例:
男人-女人【一对多】
男人-爱好【多对多】
4.Man.java
@Entity @Table(name = "t_man") public class Man { @Id//主键 @GeneratedValue(strategy = GenerationType.IDENTITY)//自增长 private int id; private String name; //【主控方:一对多】男人有多个女人关系由 man 维护 @OneToMany(mappedBy = "man") private List<Women> womens; //【主控方:多对多】男人可以有多重爱好,爱好同时又属于多个男人 @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)//级联保存,懒加载 //会创建一个man_hobby的维护表,关联man和hobby的id关系 @JoinTable(name = "man_hobby", joinColumns = {@JoinColumn(name = "man_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "hobby_id", referencedColumnName ="id")}) private List<Hobby> hobbies; }
5.Women.java
@Entity @Table(name = "t_women") public class Women { @Id//主键 @GeneratedValue(strategy = GenerationType.IDENTITY)//自增长 private int id; private String name; //【被控方:多对一】女人对男人 @ManyToOne @JoinColumn(name = "manan_id", referencedColumnName = "id")//外键名称,参考主键 private Man man; }
6.Hobby.java
@Entity @Table(name = "t_hobby") public class Hobby { @Id//主键 @GeneratedValue(strategy = GenerationType.IDENTITY)//自增长 private int id; private String name; //【被控方:多对多】由被控方维护关系 @ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "hobbies",fetch = FetchType.LAZY) private List<Man> mans; }