Hibernate多对多关系

2018-11-16  本文已影响0人  zealscott

使用注解用Hibernate自动创建多对多数据表。

之前我们用hibernate连接已经创建的数据表,并避免了直接写SQL语言。

同样,对于多对多的关系映射,我们可以直接在程序中定义这种对象的关系,然后JPA会自动帮助我们创建表和相关关系。

创建项目

设置xml

项目结构

54233528722

我们以老师和学生多对多的关系举例

学生

package Entity;

import javax.persistence.*;
import java.io.Serializable;

import java.util.Date;
import java.util.Set;

@Entity
//@Table(name = "t_student")
//@SequenceGenerator(name = "SEQ_STUDENT", sequenceName = "SEQ_STUDENT")

public class Student implements Serializable {
    private static final long serialVersionUID = 2524659555729848644L;
    private Long id;
    private String name;
    private Date birthday;
    private int sex;
    private String address;
    private Set<Teacher> teacherList;

    private Integer a;


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, precision = 22, scale = 0)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Temporal(TemporalType.DATE)
    @Column(name = "birthday")
    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Column(name = "sex")
    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    @Column(name = "address")
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "t_teacher_student",
            joinColumns = @JoinColumn(name = "stu_id",referencedColumnName="id"),
            inverseJoinColumns = @JoinColumn(name = "teacher_id",referencedColumnName ="id"))
    public Set<Teacher> getTeacherList() {
        return teacherList;
    }

    public void setTeacherList(Set<Teacher> teacherList) {
        this.teacherList = teacherList;
    }
}

老师

package Entity;
import Entity.Student;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;

@Entity
//@Table(name = "t_teacher")
//@SequenceGenerator(name = "SEQ_TEACHER", sequenceName = "SEQ_TEACHER")

public class Teacher implements Serializable {
    private static final long serialVersionUID = 2297316923535111793L;
    private Long id;
    private String name;
    private int sex;
    private Set<Student> studentList;

    @Id
//    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_TEACHER")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, precision = 22, scale = 0)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "sex")
    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    @ManyToMany(mappedBy = "teacherList", cascade = CascadeType.ALL)
    public Set<Student> getStudentList() {
        return studentList;
    }

    public void setStudentList(Set<Student> studentList) {
        this.studentList = studentList;
    }
}

Main

import Entity.Student;
import Entity.Teacher;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.util.HashSet;
import java.util.Set;

public class Main {


    public static void main(final String[] args) throws Exception {
        //创建配置对象(读取配置文档)
        Configuration config = new Configuration().configure();
        //创建会话工厂对象
        SessionFactory sessionFactory = config.buildSessionFactory();
        //会话对象
        Session session = sessionFactory.openSession();
        //这是开启Session的操作
        session.beginTransaction();
        Student s = new Student();
        s.setName("小猪");
        Teacher t = new Teacher();
        t.setName("小李");
        Set<Teacher> t_set = new HashSet<Teacher>();
        t_set.add(t);
        s.setTeacherList(t_set);
        session.save(s);
        //此处才是真正与数据库交互的语句
        session.getTransaction().commit();

        session.close();

    }
}

运行

运行后,打印SQL语句,发现hibernate帮我们创建了表,并添加了数据

54233533508

在shell中查看数据:

54233536532

参考

  1. hibernate多对多关系

  2. 理解JPA注解@GeneratedValue

上一篇下一篇

猜你喜欢

热点阅读