首页 > 代码库 > JPA学习---第十一节:JPA中的多对多双向关联实体定义与注解设置及操作

JPA学习---第十一节:JPA中的多对多双向关联实体定义与注解设置及操作

1、定义实体类,代码如下:

(1)、学生实体类:

package learn.jpa.entity;import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinTable;import javax.persistence.ManyToMany;import javax.persistence.JoinColumn;/** * @doc 多对多关系是对等的,认为决定谁是维护段,谁是被维护段 *       通过中间表(中间表)来关联它们之间的关系 */@Entitypublic class Student {    private int id;    private String name;    private Set<Teacher> teacher = new HashSet<Teacher>();        public Student() {        super();    }    public Student(String name) {        this.name = name;    }        @Id    @GeneratedValue    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    @Column(length=10,nullable=false)    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    /**     * inverseJoinColumns 与被维护端关联外键     * joinColumns 与维护段关联外键     */    @ManyToMany(cascade=CascadeType.REFRESH)    @JoinTable(name="student_teacher",inverseJoinColumns=@JoinColumn(name="teacher_id"),joinColumns=@JoinColumn(name="student_id"))    public Set<Teacher> getTeacher() {        return teacher;    }    public void setTeacher(Set<Teacher> teacher) {        this.teacher = teacher;    }        // 建立老师和学生的关系    public void addTeacher(Teacher teachers){        this.teacher.add(teachers);    }        // 解除老师和学生的关系    // 删除 teacher 是根据 id来删除的,所有在 Teacher 类中要重写 equals() 和 hashCode()    public void removeTeacher(Teacher teachers){        if(this.teacher.contains(teachers)){            this.teacher.remove(teachers);        }    }}

(2)、老师实体类:

package learn.jpa.entity;import java.util.HashSet;import java.util.Set;import javax.persistence.CascadeType;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Teacher {    private int id;    private String name;    private Set<Student> student = new HashSet<Student>();        // 如果声明了有参数的构造函数,那么一定要声明无参构造函数    public Teacher(){}        public Teacher(String name){        this.name = name;    }        @Id    @GeneratedValue    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    @Column(length=10,nullable=false)    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    @ManyToMany(cascade=CascadeType.REFRESH,mappedBy="teacher")    public Set<Student> getStudent() {        return student;    }    public void setStudent(Set<Student> student) {        this.student = student;    }    @Override    public int hashCode() {        final int prime = 31;        int result = 1;        result = prime * result + id;        return result;    }    @Override    public boolean equals(Object obj) {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;        Teacher other = (Teacher) obj;        if (id != other.id)            return false;        return true;    }    }

2、相关操作类,代码如下:

package learn.jpa.test;import static org.junit.Assert.*;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import learn.jpa.entity.Student;import learn.jpa.entity.Teacher;import org.junit.Test;public class ManyToManyTest {    /**     * 测试数据库是否可以生成表     */    @Test    public void test() {        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        factory.close();    }    @Test    public void save(){        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        EntityManager em = factory.createEntityManager();        em.getTransaction().begin();   // 开启事务        em.persist(new Student("xx"));        em.persist(new Teacher("xiuliu"));        em.getTransaction().commit();        em.close();        factory.close();    }        /**     * 建立老师和学生的关系(将关联的字段数据保存到中间表中)     */    @Test    public void buildTS(){        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        EntityManager em = factory.createEntityManager();        em.getTransaction().begin();   // 开启事务        // 处于托管状态,可以对数据进行更新        Student student = em.find(Student.class, 1);        student.addTeacher(em.getReference(Teacher.class, 1));        em.getTransaction().commit();        em.close();        factory.close();    }        // 解除老师和学生的关系    @Test    public void deleteTS(){        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        EntityManager em = factory.createEntityManager();        em.getTransaction().begin();   // 开启事务        // 处于托管状态,可以对数据进行更新        Student student = em.find(Student.class, 1);        student.removeTeacher(em.getReference(Teacher.class, 1));        em.getTransaction().commit();        em.close();        factory.close();    }        // 删除老师    @Test    public void deleteTeacher(){        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        EntityManager em = factory.createEntityManager();        em.getTransaction().begin();   // 开启事务        // 处于托管状态,可以对数据进行更新        // 先解除老师和学生的关系,在删除老师        Student student = em.find(Student.class, 1);        Teacher teacher = em.getReference(Teacher.class, 1);        student.removeTeacher(teacher);        em.remove(teacher);        em.getTransaction().commit();        em.close();        factory.close();    }        // 删除学生    @Test    public void deleteStudent(){        EntityManagerFactory factory = Persistence.createEntityManagerFactory("learn_jpa");        EntityManager em = factory.createEntityManager();        em.getTransaction().begin();   // 开启事务        Student student = em.getReference(Student.class, 1);        em.remove(student);        em.getTransaction().commit();        em.close();        factory.close();    }}

JPA学习---第十一节:JPA中的多对多双向关联实体定义与注解设置及操作