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;
    }
}

 

hibernate关系配置,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。