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"
"http://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 class="native" />
        </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"
"http://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 class="native" />
  </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"
          "http://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();
 }

}

 

 

时间: 2024-08-03 16:59:05

hibernate中many-to-many基本操作的相关文章

Python中列表的一些基本操作知识汇总

  这篇文章主要介绍了Python中列表的一些基本操作知识汇总,皆属于Python的基本功,需要的朋友可以参考下 Python最基本的数据结构是序列(列表/元组).一个序列中的每个元素都分配有一个数字- 它的位置或索引.第一个索引是0,第二个索引是1,依此类推. Python有6内置类型的序列,但最常见的是列表和元组,我们将在本教程中看到. 有一些东西可以使用所有序列类型来做.这些操作包括索引,切片,加,乘,并检查成员.此外,Python已经内置函数查找序列的长度和搜索它的最大和最小的元素. P

Hibernate中各个包的作用简介

下载Hibernate,例如2.0.3稳定版本,解压缩,可以看到一个hibernate2.jar和lib目录下有22个jar包: hibernate2.jar: Hibernate的库,没有什么可说的,必须使用的jar包 cglib-asm.jar: CGLIB库,Hibernate用它来实现PO字节码的动态生成,非常核心的库,必须使用的jar包 dom4j.jar: dom4j是一个Java的XML API,类似于jdom,用来读写XML文件的.dom4j是一个非常非常优秀的Java XML

Hibernate中新的TableGenerator 机制

从 initialValue 说起 问题的发现源自对 JPA 中 TableGenerator 的测试.测试的环境有这样几个条件: 为方便查询的测试,Employee 表格在初始化时会导入部分记录,这部分记录的主键在初始脚本中手动写好,比如 1.2.3.4.(参看文章所附示例代码中的import_data.sql 文件). Employee 实体使用 TableGenerator 主键生成器,initialValue 的值设置为 10. 在单元测试中添加新的 Employee 记录. Emplo

Hibernate学习(二)Hibernate中Session之get和load方法的真正区别

最近在学习SHH框架中的Hibernate,对Session的get和load方法,有点混不清楚,不知道区别在哪,或者对它们的区别感触不深.所以百度了一下,结果问题来了.百度的结果和实际测试的结果出入很大.主要是对get方法的说法跟实际运行的结果不一致. 先说一下观点吧: get不支持lazy,load支持lazy: 数据不存在时,get返回null,load则抛出ObjectNotFoundException异常. load方法可以返回实体的代理类实例,而get方法直接读取数据库,所以直接返回

Hibernate中load和get的区别

Hibernate中Session.load/get方法均可以根据指定的实体类和id从数据库读取记录,并返回与之对应的实体对象.其区别在于: 1.get()方法直接返回实体类,load()方法可以返回实体的代理类实例. 2.hibernate load是采用延迟机制(当lazy属性为true时) 而get不采用延迟机制(get语句马上读库) 3.找不到符合条件的数据 get方法将返回null load将会报出ObjectNotFoundExcepion 4.get支持多态查询,load只有在la

Hibernate中的Cache管理

Hibernate实现了良好的Cache机制,可以借助Hibernate内部的Cache迅速提高系统的数据读取性能. Hibernate中的Cache可分为两层:一级Cache和二级Cache. 一级Cache: Session实现了第一级Hibernate Cache,它属于事务级数据缓冲.一旦事务结束,这个Cache也随之失 效.一个Session的生命周期对应一个数据库事务或一个程序事务. Session-cache保证了一个Session中两次请求同一个对象时,取得的对象是同一个JAVA

hibernate中java.util.Date类型映射

在Hibernate中对于java.util.Date类型的映射为: java类型 Hibernate类型 Mysql类型 java.util.Date.java.sql.Date date DATE java.util.Date.java.sql.Time time TIME java.util.Date.java.sql.Timestamp timestamp TIMESTAMP 如果使用timestamp作为Date类型映射时,具体代码如下: Java代码 public class Use

Asp.Net中对Cookie的基本操作

实例代码演示Asp.Net中对Cookie的基本操作. Imports System.Web.HttpContext Public Class CookieFramework '写入单个Cookie Public Shared Function WriteCookie(ByVal CookieName As String, ByVal CookieValue As String, ByVal ExpiresDate As Integer) As Boolean Dim aCookie As Ne

Hibernate中Session的缓存及对象的状态

对于session这个接口的学习可以说是最痛苦也是最复杂的,因为它所涉及的方面太多了,一些隐藏的机制也很多,谁让它是Central API呢. 对于它的几个最基本的方法如save().delete().flush()等的学习都花了我一定的时间.在深入了解这些这些方法前,了解session的缓存机制以及Hibernate中Java对象的状态对我们是很有帮助的. 一.Session的缓存 Java是纯面向对象的语言,因此不可能像C语言那样直接操纵内存,例如声明一段可用的内存空间.在Java里面,缓存

在Hibernate中检索策略的应用详解

Hibernate的检索策略包括类级别检索策略和关联级别检索策略. 类级别检索策略有立即检索和延迟检索,默认的检索策略是立即检索.在Hibernate映射文件中,通过在<不着class>上配置lazy属性来确定检索策略.对于Session的检索方式,类级别检索策略仅适用于load方法:也就说,对于get.qurey检索,持久化对象都会被立即加载而不管lazy是false还是true.一般来说,我们检索对象就是要访问它,因此立即检索是通常的选择.由于load方法在检索不到对象时会抛出异常(立即检