java框架篇---hibernate(多对多)映射关系

 以学生和老师为例的来讲解多对多映射。

实体类:

Student
package cn.itcast.g_hbm_manyToMany;

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

public class Student {
    private Long id;
    private String name;

    private Set<Teacher> teachers = new HashSet<Teacher>();

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Set<Teacher> getTeachers() {
        return teachers;
    }

    public void setTeachers(Set<Teacher> teachers) {
        this.teachers = teachers;
    }
    @Override
    public String toString() {
        return "[Student: id=" + id + ", name=" + name + "]";
    }
}
Teacher 
package cn.itcast.g_hbm_manyToMany;

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


public class Teacher {
    private Long id;
    private String name;

    private Set<Student> students = new HashSet<Student>(); 
    
    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Set<Student> getStudents() {
        return students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }
    @Override
    public String toString() {
        return "[Teacher: id=" + id + ", name=" + name + "]";
    }
}

映射文件:

Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.itcast.g_hbm_manyToMany">
    
    <class name="Student" table="student">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name"/>
        
        <!-- teachers属性,Set集合。
            表达的是本类与Teacher的多对多。
            
            table属性:中间表(集合表)
            key子元素:集合外键(引用当前表主键的那个外键)
         -->
        <set name="teachers" table="teacher_student" inverse="false">
            <key column="studentId"></key>
            <many-to-many class="Teacher" column="teacherId"></many-to-many>
        </set>
            
    </class>
    
</hibernate-mapping>
Teacher.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="cn.itcast.g_hbm_manyToMany">
    
    <class name="Teacher" table="teacher">
        <id name="id">
            <generator class="native"></generator>
        </id>
        <property name="name" type="string" column="name"/>
        
        <!-- students属性,Set集合。
            表达的是本类与Student的多对多。
         -->
        <set name="students" table="teacher_student" inverse="true">
            <key column="teacherId"></key>
            <many-to-many class="Student" column="studentId"></many-to-many>
        </set>
        
    </class>
    
</hibernate-mapping>

测试

App.java
package cn.itcast.g_hbm_manyToMany;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

import com.java1234.util.HibernateSessionFactory;

public class App {

    private static SessionFactory sessionFactory =HibernateSessionFactory.getSessionFactory();

    // 保存,有关联关系
    @Test
    public void testSave() throws Exception {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        // --------------------------------------------

        // 新建对象
        Student student1 = new Student();
        student1.setName("王同学1");

        Student student2 = new Student();
        student2.setName("李同学2");

        Teacher teacher1 = new Teacher();
        teacher1.setName("赵老师3");

        Teacher teacher2 = new Teacher();
        teacher2.setName("蔡老师4");

        // 关联起来
        student1.getTeachers().add(teacher1);
        student1.getTeachers().add(teacher2);
        student2.getTeachers().add(teacher1);
        student2.getTeachers().add(teacher2);

        teacher1.getStudents().add(student1);
        teacher1.getStudents().add(student2);
        teacher2.getStudents().add(student1);
        teacher2.getStudents().add(student2);

        // 保存
        session.save(student1);
        session.save(student2);
        session.save(teacher1);
        session.save(teacher2);

        // --------------------------------------------
        session.getTransaction().commit();
        session.close();
    }

    // 获取,可以获取到关联的对方
    @Test
    public void testGet() throws Exception {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        // --------------------------------------------

        // 获取一方,并显示另一方信息
        Teacher teacher = (Teacher) session.get(Teacher.class, 3L);
        System.out.println(teacher);
        System.out.println(teacher.getStudents());

        // --------------------------------------------
        session.getTransaction().commit();
        session.close();

    }

    // 解除关联关系
    @Test
    public void testRemoveRelation() throws Exception {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        // --------------------------------------------

        // 如果inverse=false就可以解除,如果为true就不可以解除
        Teacher teacher = (Teacher) session.get(Teacher.class, 3L);
        teacher.getStudents().clear();

        // --------------------------------------------
        session.getTransaction().commit();
        session.close();
    }

    // 删除对象,对关联对象的影响
    @Test
    public void testDelete() throws Exception {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        // --------------------------------------------

        // a, 如果没有关联的对方:能删除。
        // b, 如果有关联的对方且inverse=false,由于可以维护关联关系,他就会先删除关联关系,再删除自己。
        // c, 如果有关联的对方且inverse=true,由于不能维护关联关系,所以会直接执行删除自己,就会有异常。
        Teacher teacher = (Teacher) session.get(Teacher.class, 9L);
        session.delete(teacher);

        // --------------------------------------------
        session.getTransaction().commit();
        session.close();
    }

}

两张表的多对多关系,在数据库中通常是通过第三张中间表来实现的,第三张中间表放的是两张表各自的主键值,通过主键与主键的对应来体现表直接的关系。比如在权限系统中,一个用户可以拥有多种权限,而一种权限也可以授予多个用户。

你可能感兴趣的:(Hibernate)