閱讀1008 返回首頁    go 阿裏雲 go 技術社區[雲棲]


hibernate中many-to-many基本操作

創建數據庫

create database student;
use student;
create table studentInfo(
       stuNo integer auto_increment not null primary key,
       stuName varchar(50) not null
);
create table courseInfo(
       courseNo integer auto_increment not null primary key,
       courseName varchar(30) not null
);
create table student_course(
       stuNo int,
       courseNo int,
       foreign key(stuNo) references studentInfo(stuNo),
       foreign key(courseNo) references courseInfo(courseNo)
);
show databases;

 

Pojo

package com.etp.zsh.pojo;

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


public class Courseinfo implements java.io.Serializable {

 private Integer courseNo;
 private String courseName;
 private Set studentinfos = new HashSet(0);


 
 public Courseinfo() {
 }

 
 public Courseinfo(String courseName) {
  this.courseName = courseName;
 }

 
 public Courseinfo(String courseName, Set studentinfos) {
  this.courseName = courseName;
  this.studentinfos = studentinfos;
 }

 // Property accessors

 public Integer getCourseNo() {
  return this.courseNo;
 }

 public void setCourseNo(Integer courseNo) {
  this.courseNo = courseNo;
 }

 public String getCourseName() {
  return this.courseName;
 }

 public void setCourseName(String courseName) {
  this.courseName = courseName;
 }

 public Set getStudentinfos() {
  return this.studentinfos;
 }

 public void setStudentinfos(Set studentinfos) {
  this.studentinfos = studentinfos;
 }

}

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.etp.zsh.pojo.Courseinfo" table="courseinfo" catalog="student">
        <id name="courseNo" type="java.lang.Integer">
            <column name="courseNo" />
            <generator />
        </id>
        <property name="courseName" type="java.lang.String">
            <column name="courseName" length="30" not-null="true" />
        </property>
        <set name="studentinfos" table="student_course" catalog="student">
            <key>
                <column name="courseNo" />
            </key>
            <many-to-many entity-name="com.etp.zsh.pojo.Studentinfo">
                <column name="stuNo" />
            </many-to-many>
        </set>
    </class>
</hibernate-mapping>


 

 

package com.etp.zsh.pojo;

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

public class Studentinfo implements java.io.Serializable {

 // Fields

 private Integer stuNo;
 private String stuName;
 private Set courseinfos = new HashSet(0);

 // Constructors

 
 public Studentinfo() {
 }

 
 public Studentinfo(String stuName) {
  this.stuName = stuName;
 }

 
 public Studentinfo(String stuName, Set courseinfos) {
  this.stuName = stuName;
  this.courseinfos = courseinfos;
 }

 // Property accessors

 public Integer getStuNo() {
  return this.stuNo;
 }

 public void setStuNo(Integer stuNo) {
  this.stuNo = stuNo;
 }

 public String getStuName() {
  return this.stuName;
 }

 public void setStuName(String stuName) {
  this.stuName = stuName;
 }

 public Set getCourseinfos() {
  return this.courseinfos;
 }

 public void setCourseinfos(Set courseinfos) {
  this.courseinfos = courseinfos;
 }

}

 

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.etp.zsh.pojo.Studentinfo" table="studentinfo"
  catalog="student">
  <id name="stuNo" type="java.lang.Integer">
   <column name="stuNo" />
   <generator />
  </id>
  <property name="stuName" type="java.lang.String">
   <column name="stuName" length="50" not-null="true" />
  </property>

  <set name="courseinfos" table="student_course" catalog="student">
   <key>
    <column name="stuNo" />
   </key>
   <many-to-many entity-name="com.etp.zsh.pojo.Courseinfo">
    <column name="courseNo" />
   </many-to-many>
  </set>
 </class>
</hibernate-mapping>

 

 HibernateSessionFactory

package com.etp.zsh.pojo;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory
{

 
 private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
 private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
 private static Configuration configuration = new Configuration();
 private static org.hibernate.SessionFactory sessionFactory;
 private static String configFile = CONFIG_FILE_LOCATION;

 static
 {
  try
  {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  }
  catch (Exception e)
  {
   System.err.println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }

 private HibernateSessionFactory()
 {
 }

 
 public static Session getSession() throws HibernateException
 {
  Session session = (Session) threadLocal.get();

  if (session == null || !session.isOpen())
  {
   if (sessionFactory == null)
   {
    rebuildSessionFactory();
   }
   session = (sessionFactory != null) ? sessionFactory.openSession() : null;
   threadLocal.set(session);
  }

  return session;
 }

 
 public static void rebuildSessionFactory()
 {
  try
  {
   configuration.configure(configFile);
   sessionFactory = configuration.buildSessionFactory();
  }
  catch (Exception e)
  {
   System.err.println("%%%% Error Creating SessionFactory %%%%");
   e.printStackTrace();
  }
 }

 
 public static void closeSession() throws HibernateException
 {
  Session session = (Session) threadLocal.get();
  threadLocal.set(null);

  if (session != null)
  {
   session.close();
  }
 }

 
 public static org.hibernate.SessionFactory getSessionFactory()
 {
  return sessionFactory;
 }

 
 public static void setConfigFile(String configFile)
 {
  HibernateSessionFactory.configFile = configFile;
  sessionFactory = null;
 }

 
 public static Configuration getConfiguration()
 {
  return configuration;
 }

}

 

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

 <!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

 <session-factory>
  <property name="show_sql">true</property>
  <property name="myeclipse.connection.profile">
   com.mysql.jdbc.Driver
  </property>
  <property name="connection.url">
   jdbc:mysql://localhost:3306/student
  </property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>
  <property name="connection.driver_class">
   com.mysql.jdbc.Driver
  </property>
  <property name="dialect">
   org.hibernate.dialect.MySQLDialect
  </property>
  <mapping resource="com/etp/zsh/pojo/Studentinfo.hbm.xml" />
  <mapping resource="com/etp/zsh/pojo/Courseinfo.hbm.xml" />

 </session-factory>

</hibernate-configuration>


 

測試類

package com.etp.zsh.pojo;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test
{
 // 實體表中插入數據
 public void testManyToMany_1()
 {
  Studentinfo s1 = new Studentinfo("張三");
  Studentinfo s2 = new Studentinfo("李四");
  Studentinfo s3 = new Studentinfo("王五");
  Courseinfo c1 = new Courseinfo("物理");
  Courseinfo c2 = new Courseinfo("數學");
  Courseinfo c3 = new Courseinfo("化學");
  Session session = null;
  Transaction tran = null;
  try
  {
   session = HibernateSessionFactory.getSession();
   tran = session.beginTransaction();
   session.save(c1);
   session.save(c2);
   session.save(c3);
   session.save(s1);
   session.save(s2);
   session.save(s3);
   tran.commit();
  }
  catch (Exception e)
  {
   // TODO: handle exception
   e.printStackTrace();
   tran.rollback();
  }
  finally
  {
   HibernateSessionFactory.closeSession();
  }
 }

 // 從Student端維護關係表
 public void testManyToManay_2()
 {
  Session session = null;
  Transaction tran = null;
  try
  {
   session = HibernateSessionFactory.getSession();
   tran = session.beginTransaction();
   Studentinfo st = (Studentinfo) session.get(Studentinfo.class, 1);
   Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 2);
   st.getCourseinfos().add(cs);
   tran.commit();
  }
  catch (Exception e)
  {
   e.printStackTrace();
   tran.rollback();
  }
  finally
  {
   HibernateSessionFactory.closeSession();
  }
 }

 // 從課程端維護
 public void testManyToMany_3()
 {
  Session session = null;
  Transaction tran = null;
  try
  {
   session = HibernateSessionFactory.getSession();
   tran = session.beginTransaction();
   Studentinfo st = (Studentinfo) session.get(Studentinfo.class, 2);
   Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 1);
   cs.getStudentinfos().add(st);
   tran.commit();
  }
  catch (Exception e)
  {
   // TODO: handle exception
   e.printStackTrace();
   tran.rollback();
  }
  finally
  {
   HibernateSessionFactory.closeSession();
  }
 }

 // 從關係表中刪除數據
 // 而實體表中不會有變化
 public void DeleteFromRelationTable()
 {
  Session session = null;
  Transaction tran = null;
  try
  {
   session = HibernateSessionFactory.getSession();
   tran = session.beginTransaction();

   // 刪除學號為1,課程號為2的關係表中的記錄(從學生端維護)
   Studentinfo stu = (Studentinfo) session.createQuery

                       ("from Studentinfo s where s.stuNo = 1").uniqueResult();
   Courseinfo cs = (Courseinfo) session.get(Courseinfo.class, 2);
   stu.getCourseinfos().remove(cs);

 

   // 刪除學號為1的同學關聯表中所有相關記錄
   Studentinfo s = (Studentinfo) session.createQuery

                     ("from Studentinfo s where s.stuNo = 1").uniqueResult();
   s.getCourseinfos().clear();
  
   // 刪除課程為2的課程關聯表中所有相關記錄
   Courseinfo c = (Courseinfo) session.get(Courseinfo.class, 2);
   c.getStudentinfos().clear();
  
   tran.commit();
  }
  catch (Exception e)
  {
   e.printStackTrace();
   tran.rollback();
  }
  finally
  {
   HibernateSessionFactory.closeSession();
  }

 }

 public static void main(String[] args)
 {
  Test t = new Test();
  // t.testManyToMany_1();
  // t.testManyToMany_2();
  t.DeleteFromRelationTable();
 }

}


 

 

最後更新:2017-04-02 06:52:16

  上一篇:go Sql Server中如何取得剛剛插入的自增長的id值
  下一篇:go Java時間幫助類DateUtil