Danial7777777

导航

hibernate多对多关系

package com.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 + "]";
    }
}
package com.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 + "]";
    }
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.manytomany">
    <class name="Student" table="t_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>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.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>
package com.manytomany.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.EnumSet;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import com.hello.Account;
import com.hello.User;
import com.manytomany.Student;
import com.manytomany.Teacher;

public class HelloTest {

    private static SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration()
        .configure() // 读取配置文件
        .buildSessionFactory();
    }

    // 根据配置生成表结构
    @Test
    public void test() {
        //hibernate 5.0
        Configuration conf = new Configuration().configure();//1、读取配置文件
        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
        Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
    }

    @Test
    public void hello(){


        Session session=sessionFactory.openSession();
        Transaction tx = session.beginTransaction();
        //==================================================
        Student student1 = new Student();
        student1.setName("王同学");

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

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

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

        // 关联起来
        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);

        //==================================================
        tx.commit();
    }


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

        // 如果inverse=false就可以解除,如果为true就不可以解除(删除中间表中的记录)
        //        Teacher teacher = (Teacher) session.get(Teacher.class, 3L);
        //        teacher.getStudents().clear();
        Student student=session.get(Student.class, 4l);
        student.getTeachers().clear();

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

        // 删除老师方
        // a,如果没有关联的对方:能删除
        // b,如果有关联的对方且inverse=false,由于可以维护关联关系,它就会先删除关联关系,再删除自己。
        // c,如果有关联的对方且inverse=true,由于不能维护关联关系,所以会直接执行删除自己,就会有异常
//        Teacher teacher = (Teacher) session.get(Teacher.class, 5L);
//        session.delete(teacher);
        Student student=session.get(Student.class, 6l);
        session.delete(student);
        // -------------------------------------------
        session.getTransaction().commit();
        session.close();
    }


    @Test
    public void testGet(){

        Session session=sessionFactory.openSession();

    }
}
删除打印sql语句
Hibernate: 
    select
        student0_.id as id1_1_0_,
        student0_.name as name2_1_0_ 
    from
        t_student student0_ 
    where
        student0_.id=?
Hibernate: 
    delete 
    from
        teacher_student 
    where
        studentId=?
Hibernate: 
    delete 
    from
        t_student 
    where
        id=?

 

posted on 2018-07-21 15:17  Danial7777777  阅读(171)  评论(0编辑  收藏  举报