首页 > 代码库 > hibernate关系配置
hibernate关系配置
hibernate中关系的映射有多种,一对一,一对多/多对一,多对多,其中还分单向和双向,其实简单来讲,如果你想获得另一个对象的引用,你就可以在类中定义一个该对象或
该对象的集合。至于表中的关系就是在多方存你的外键而已,如果是多对多,则建立一个中间表,用来存两个关联对象的外键。
一对多&多对一双向
双向关联,在单方设置mapped,将关系由多方主导Group.java
@Entity @Table(name="t_group") public class Group { private int id; private String name; private Set<User> users = new HashSet<User>(); @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="group") public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
User.java
@Entity @Table(name="t_user") public class User { private int id; private String name; private Group group; @ManyToOne public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @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; }
多对多设置中间表"t_s"
Student.java
@Entity public class Student { private int id; private String name; private Set<Teacher> teachers = new HashSet<Teacher>(); @ManyToMany(mappedBy="students") public Set<Teacher> getTeachers() { return teachers; } public void setTeachers(Set<Teacher> teachers) { this.teachers = teachers; } @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; } }
Teacher.java
@Entity public class Teacher { private int id; private String name; private Set<Student> students = new HashSet<Student>(); @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; } @ManyToMany @JoinTable(name="t_s", joinColumns={@JoinColumn(name="teacher_id")}, inverseJoinColumns={@JoinColumn(name="student_id")} ) public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。