hibernate中多对多相关配置

释放双眼,带上耳机,听听看~!
 平常生活中多对多的情况很常见,如一个老师有多个学生,一个学生也有多个老师,对于这种较复杂的情况,在hibernate中完成持久化时也比其他的情况稍有复杂。下面进行相关的说明。

1、学生实体类:

public class Student {

    private int id;
    private String name;
    private String sex;
    private int grade;
    private Set<Teacher> teachers;//一个学生可以有多个老师
//下面一些get/set方法
}

2、老师实体类:

public class Teacher {

    private int id;
    private String name;
    private String sex;
    private int age;
    private Set<Student> students;//一个老师也有许多学生。
//下面一些get/set方法
}

3、学生实体类的配置文件:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>

   <class name="com.bean2.Student" table="student_s" >
          <!-- 主键 -->
          <!-- 
              name:  属性名
              column:映射到数据库的列名,默认是属性名
          -->
          <id name="id" column="id"  type="int">
               <!-- 主键生成策略 -->
               <generator class="native"></generator>
          </id>

      <property name="name" type="java.lang.String"></property>
      <property name="grade" type="int"></property>
      <property name="sex" type="string"></property>
      <!-- cascade这个属性不能少 -->
      <set name="teachers" table="students_teacher" cascade="all">
        <key column="student_id"></key>
        <many-to-many class="com.bean2.Teacher" column="teacher_id"></many-to-many>
      </set>
   </class>

 </hibernate-mapping>

4、老师实体类的配置文件与学生实体类的配置文件类似:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <hibernate-mapping>
  <class name="com.bean2.Teacher" table="teacher_s">
    <id name="id">
      <generator class="native"></generator>
    </id>
    <property name="name" type="string"></property>
    <property name="sex" type="string" ></property>
    <property name="age" type="int"></property>
          <!-- cascade这个属性不能少 -->
    <set name="students" table="students_teacher" cascade="all">
       <key column="teacher_id"></key>
       <many-to-many class="com.bean2.Student" column="student_id" ></many-to-many>
    </set>
  </class>
 </hibernate-mapping>

5、测试类的编写
1)、获取session对象的工具类:


package com.util;

import org.hamcrest.Factory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
*包名:com.util.HibernateUtil.java
*描述:
*作者:
*日期:2016年7月3日
*时间:下午9:23:07
*/

public class HibernateUtil {

    private static Configuration cfg = null;
    private static SessionFactory factory = null;
    static{
        cfg = new Configuration().configure("hibernate.cfg.xml");
        factory = cfg.buildSessionFactory(); 
    }

    public static Session getSession(){
        return factory.openSession();
    }
}

2)、测试代码:
正确的测试代码,如下:


package com.test;

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

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.bean2.Student;
import com.bean2.Teacher;
import com.util.HibernateUtil;

/**
*包名:com.test.TestMany.java
*描述:
*作者:
*日期:2016年7月6日
*时间:下午8:44:46
*/

public class TestMany {

    @Test
    public void testManySave(){
        Session session = HibernateUtil.getSession();
        Transaction tran = session.beginTransaction();
        Student s = new Student();
        s.setName("张志明");
        s.setSex("男");
        s.setGrade(5);
        Teacher t = new Teacher("李华", "男", 50);
        Teacher t2 = new Teacher("张晓敏", "女", 23);
        Set<Student> st = new HashSet<>();
        st.add(s);
        //t.setStudents(st);
        //t2.setStudents(st);
        Set<Teacher> tset = new HashSet<>();
        tset.add(t2);
        tset.add(t);
        s.setTeachers(tset);
        session.save(s);
        tran.commit();
        session.close();

    }
}

通过查看数据库中的数据可以发现数据保存成功,相关配置正确。表中数据如下:

hibernate中多对多相关配置

错误的测试代码,在老师和学生对象中只需一方来维护这种关系,若两方维护则会产生异常。错误测试代码如下:


@Test
    public void testManySave(){
        Session session = HibernateUtil.getSession();
        Transaction tran = session.beginTransaction();
        Student s = new Student();
        s.setName("张志明");
        s.setSex("男");
        s.setGrade(5);
        Teacher t = new Teacher("李华", "男", 50);
        Teacher t2 = new Teacher("张晓敏", "女", 23);
        Set<Student> st = new HashSet<>();
        st.add(s);
        t.setStudents(st);
        t2.setStudents(st);
        Set<Teacher> tset = new HashSet<>();
        tset.add(t2);
        tset.add(t);
        s.setTeachers(tset);
        session.save(s);
        tran.commit();
        session.close();

    }
//上面这段代码出错的原因在于
//      (t.setStudents(st);t2.setStudents(st);)和
//s.setTeachers(tset);同时存在,这两小段代码取其一即可。
//若同时存在,依据上面的代码,则会在students_teacher表中
//插入三次数据,实际只需两次即可。

在上面代码的注释中提到的问题不解决会产生如下的错误:

org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1313)
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:560)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:434)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1295)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:468)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3135)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2352)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:485)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:147)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:65)
    at com.test.TestMany.testManySave(TestMany.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:276)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:48)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:244)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:59)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:242)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:49)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:235)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:305)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '3-1' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2427)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2345)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2330)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204)
    ... 40 more

并且控制台输出的SQL语句就可以明显的看出问题:

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Hibernate: 
    insert 
    into
        student_s
        (name, grade, sex) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        teacher_s
        (name, sex, age) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        teacher_s
        (name, sex, age) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        students_teacher
        (student_id, teacher_id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        students_teacher
        (student_id, teacher_id) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        students_teacher
        (teacher_id, student_id) 
    values
        (?, ?)
七月 06, 2016 10:00:51 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000

从输出的SQL中就可以看出,往students_teacher表中插入了三次,一个学生有两个老师,明显只需插入2次即可。解决的办法就是二选一。

写的不好,还望各位看官别介意!!

【转自慕课】https://www.imooc.com

JAVA

通俗易懂的阿里Sentinel源码分析:如何向控制台发送心跳包?

2022-3-3 11:02:27

JAVA

leetcode算法14.最长公共前缀

2022-3-3 11:07:54

搜索