Admin类:
@Entity @Table(name="t_admin") public class Admin { private int id; private String name; private Set<AdminRole> ars; public Admin() { ars = new HashSet<AdminRole>(); } public void add(AdminRole ar) { ars.add(ar); } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="admin") ---> OneToMany关联到了AdminRole这个类,由AdminRole这个类来维护多对一的关系,mappedBy="admin" @LazyCollection(LazyCollectionOption.EXTRA) public Set<AdminRole> getArs() { return ars; } public void setArs(Set<AdminRole> ars) { this.ars = ars; } }Role类:
@Entity @Table(name="t_role") public class Role { private int id; private String name; private Set<AdminRole> ars; public Role() { ars = new HashSet<AdminRole>(); } public void add(AdminRole ar) { ars.add(ar); } @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @OneToMany(mappedBy="role") ---> OneToMany指定了由AdminRole这个类来维护多对一的关联关系,mappedBy="role" @LazyCollection(LazyCollectionOption.EXTRA) public Set<AdminRole> getArs() { return ars; } public void setArs(Set<AdminRole> ars) { this.ars = ars; } }AdminRole类:
@Entity @Table(name="t_admin_role") public class AdminRole { private int id; private String name; private Admin admin; private Role role; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne ---> ManyToOne关联到Admin @JoinColumn(name="aid") public Admin getAdmin() { return admin; } public void setAdmin(Admin admin) { this.admin = admin; } @ManyToOne ---> @JoinColumn(name="rid") public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }小技巧:通过hibernate来进行插入操作的时候,不管是一对多、一对一还是多对多,都只需要记住一点,在哪个实体类声明了外键,就由哪个类来维护关系,在保存数据时,总是先保存的是没有维护关联关系的那一方的数据,后保存维护了关联关系的那一方的数据
4.中间表两个实体tb_user,tb_role
现在我们再tb_user或者tb_role中任意一个里面进行维护关系,多对对的情况下我们需要创建一个中间表来完成这个关系的映射,我们再tb_user中添加注解@ManyToMany然后再添加一个注解@JoinTable因为我们是要创建中间表所以要使用这个注解。JoinTable注解中我们添加如下例子中的内容,joinColumns当前表中的字段在中间表中的字段名称,inverseJoinColumns关联的外键表在中间表中的字段名称