Hibernate实验指导
- 格式:doc
- 大小:1.03 MB
- 文档页数:72
J2EE项目实训Hibernat...第二章Hibernate框架主要的核心API(第1/2部分)Hibernate框架是完整的对象/关系映射解决方案,它提供了对象状态管理的功能,使开发者不再需要了解和把握后台物理数据库系统的数据管理和存储等方面的技术细节。
也就是说,相对于常规的JDBC/SQL模式的持久层方案中需要管理SQL语句而言,Hibernate 框架则采用了更自然的面向对象的技术来持久化基于Java开发平台的应用系统中的持久化数据。
从而达到使用Hibernate框架的开发者应该或者也只需要关注持久化对象目前所处的状态,而不必需要再考虑SQL语句的执行情况。
在Hibernate框架中,为需要进行持久化的对象定义了三种状态:瞬时(transient,临时)、持久(persistent)和脱管(detached或者称为“游离态”)。
一个持久化类的对象实例在运行时可能处于三种不同状态中的某一种,而开发者在改变对象的状态时,需要利用Hibernate框架中的一些核心API。
另外,Hibernate框架对数据库的基本操作主要是依赖下面的五个核心接口和类:Configuration、SessionFactory、Session、Transaction、Query和Criteria。
而对于这些接口和类的学习,是掌握Hibernate框架技术进行应用系统开发的基本技术基础。
在本章,我们将进一步深入地学习和掌握Hibernate框架中的各个主要的核心API接口和类的编程及具体的应用,以及在实际开发应用中所应该注意的问题等方面的内容。
1.1与系统初始化相关的各个接口和类1.1.1Configuration 类1、Configuration类的作用是实现对Hibernate框架系统进行配置(1)主要的作用配置Hibernate框架并预启动Hibernate框架,从而最终达到创建SessionFactory对象。
目录新建数据库和表在数据库test 中创建student 表格创建 HibernateDemo Java Project新建一个Java Project命名为:HibernateDemo添加Hibernate Capabilities 到现有项目像添加Spring和Struts支持一样,给项目添加Hibernate Capabilities点击”next”再点击”next”选择好“DB Driver”点击“next”新建一个package得到:点击“Finish”使用反向工程快速生成Java POJO 类,映射文件和DAO找到DB Browser选择我们创建的student表右键点击出现下图:选择“Hibernate Reverse Engineering”出现:在Java Package那里通过“Browser”找到项目的dao包按顺序将要打勾的地方打上勾点击1 处的Java src folder 最右侧的Browse 按钮,查看可用的Hibernate 项目以及源码目录,这些目录将用来存放最终生成的文件。
这里选中HibernateDemo 项目中的src 文件夹.。
点击2 处的Java package 输入框右侧的Browse 按钮,选中dao 包,或者新建一个其它的包来存放生成的代码所在的包。
将3 中的两个复选框选中,这样将为每个数据库表生成Hibernate 映射文件(*.hbm.xml),并在hibernate.cfg.xml 中将新生成的映射文件加入。
在4 中选中复选框Java Data Object(POJO <> DB Table),这样为映射文件和表格生成对应的数据对象(POJO)。
按照图示选中5 处的复选框,这样将能生成普通的DAO 类。
点击“Finish”看到:编写测试类在项目文件夹中新建一个类:学写第一个HQL语句如下图在HQL 1 中输入“From Student s where s.id = 1”。
实验八 Session缓存及对象-关系映射(多对一)实验一、实验目的:理解Hibernate Session缓存,掌握Hibernate程序实现对象-关系映射(多对一单向映射)的步骤和过程。
二、实验内容:1在MyEclipse环境下编写Java代码,运用Hibernate完成具有关联关系的JavaBean对象的添加、更新、读取显示和删除功能,调试运行程序。
2 在MyEclipse环境下通过debug运行模式,观察Hibernate 发送SQL语句的时机三、实验要求:1. 进一步熟悉并掌握Hibernate程序的编写步骤;2. 运用Hibernate常用API及hibernate.cfg.xml、对象-关系映射文件和持久化类技术完成规定功能;3. 写出实验报告。
四、实验学时:2学时五、实验步骤:实验内容一步骤1. 在实验七的基础上,开发封装书籍表信息的持久化Book JavaBean,并建立与出版社Publisher JavaBean的多对一单向关联关系2. 在实验七基础上,开发用以实现Book类与数据库书籍表进行映射的对象-关系映射文件3. 开发BookTest测试类方法,实现以下功能3.1 书籍基本信息的添加;3.2 获取一条书籍基本信息,包括关联的出版社信息3.3 更新一条书籍信息3.4 删除一条书籍信息4. 运行调试程序实验内容二步骤:1. 导入Hibernate PPT4 (Hibernate持久化对象状态和Session缓存)示例Hibernate_SessionCache2. 设置断点,利用debug模式运行示例中的testUpdateStudent3、testUpdateStudent4、testUpdateStudent5和testUpdateStudent6方法,观察并解释Hibernate发送SQL语句的时机和现象六、选作实验1. 利用JPA注解替代实验中的对象-关系映射文件。
第九章对基于Hibernate的DAO单元测试(第2/3部分)1.1对基于Hibernate框架技术的DAO组件单元测试1.1.1DAO组件单元测试的测试要点1、对基于Hibernate框架技术的DAO组件的单元测试的内容对基于Hibernate框架技术的DAO组件的单元测试的内容,主要涉及如下两个方面的测试。
(1)对其hibernate.cfg.xml文件以及各个 O/R Mapping(对象/关系映射)的各种*.xml 文件的测试(2)对基于Hibernate框架技术的DAO组件中的各个数据访问功能(CRUD)的方法进行测试。
2、测试要点在测试用例类中利用Configuration类中的configure()方法来定位被测试系统的hibernate.cfg.xml文件,从而获得SessionFactory,最后获得Session。
3、对各个*.xml文件进行测试的测试用例的基本模板程序下面的【例9-4】所示为对基于Hibernate框架技术的DAO组件的各个*.xml文件进行测试的测试用例的基本模板程序。
【例9-4】测试用例的基本模板程序示例,并请注意其中的黑体部分的代码。
package com.px1987.junit.test;import junit.framework.TestCase;import java.io.*;import org.hibernate.cfg.*;import org.hibernate.*;public class TestHibernateXML extends TestCase {protected void setUp() throws Exception {super.setUp();}protected void tearDown() throws Exception {super.tearDown();}public void testHibernateXML(){SessionFactory sessionFactory=null;Session oneSession=null;String hibernateXMLFile="D:\\HibernateExmp\\EclipseJ2SEApp\\hibernate.cfg.xml"; //根据实际改变File xmlFile=new File(hibernateXMLFile);Configuration config = new Configuration().configure(xmlFile);sessionFactory=config.buildSessionFactory();this.assertNotNull(sessionFactory);oneSession=sessionFactory.openSession();this.assertNotNull(oneSession);}}1.1.2DAO组件单元测试的测试示例为了使读者对如何利用JUnit单元测试框架对基于Hibernate框架的DAO组件的单元测试有所掌握,下面给出一个针对本书的第一章中的【例1-19】所示的HibernateDAOBean 组件类,在Eclipse中开发工具中实现对其单元测试的实现过程。
实践1 清楚缓存对象-clear()方法
实验目的
在添加批量数据时,采用Clear方法在适当的时候清空缓存,以提高的系统的性能,防止内存被占用过多,导致内存溢出异常。
技术要点
●SQL基础知识;
●Hibernate基础知识。
实验步骤
1.打开项目HibernateProject05,在hibernate.cfg.xml中添加如下属性:
2.
3.修改StudentManager.java的主函数,代码如下:
4.运行StudentManager,查看执行结果
实践2 清楚缓存对象-evict()方法实验目的
采用evict()方法清除缓存中的某个具体的对象
技术要点
●SQL基础知识;
●Hibernate基础知识。
实验步骤
1.在StudentDAO中加入如下方法:
2.修改StudentManager.java的主函数,代码如下:
3.运行StudentManager,查看执行结果。
Hibernate实验(一):数据源、Hibernate配置与反向工程映射实验目的:1、熟练掌握Eclipse中数据源的配置。
2、熟练掌握Hibernate配置、理解配置文件内容。
3、熟悉掌握反向工程的概念,并能完成反向工程的相关ORMapping操作。
4、初步了解应用Hibernate架构技术完成数据库应用项目开发。
实验内容:参考下列步骤将示例项目:TeacherSysDemo再做一遍。
一.建立数据库如果该数据库已存在,此步骤可省略。
注意:也可以使用提供的salary.bak在SQLServer中进行“还原数据库”操作在SQLServer中建立数据库teacherinfo。
表结构与样例数据参考如下:二、新建项目新建一个Dynamic Web Project项目Hibernatepro1,并将示例项目如:TeacherSysDemo中WebContent目录中WEB-INFO中lib下所有的.jar文件拷贝到此新建项目对应的文件夹中。
三、数据源配置在Eclipse菜单项中选择Window->Show View->Data Source Explorer使之配置成如下效果:参考配置过程与参考选项值设置:点击其中Test Connection按钮,应得到Ping Success即为数据源配置成功。
记录其中的Connection URL。
用于后续Hibernate配置。
三、在Eclipse中进行Hibernate数据库连接配置与Hibernate.xml文件配置1.打开Hibernate Configurations面板Hibernate插件安装完毕后,Windows->Show View->Hibernate->Hibernate Configurations点击OK后,出现Hibernate Configurations面板:2.进行hibernate配置在该面板中点击右键菜单中“Add Configuration”菜单项:3.hibernate.cfg.xml文件的生成要先有hibernate.cfg.xml文件,才能为后续反向工程映射文件的生成提供条件。
实验12Java Web 应用开发入门12.1 实验目标1.配置Hibernate4的开发环境,初步认识Hibernate应用的程序结构。
2.了解Hibernate程序开发的步骤,了解SessionFactory等主要类和配置文件。
3.开发一个简单的应用程序并运行测试它。
12.2 准备工作1.获取Hibernate访问Hibernate官网:/downloads.html,下载发行包,如图12.1。
图12.1 下载Hibernate发行包将下载的压缩包解压到某一个目录,下面以${Hibernate_Home}表示该目录。
2.使用Hibernate开发Java应用的主要步骤1)创建Hibernate配置文件:hibernate.cfg.xml配置文件hibernate.cfg.xml用来设置数据库的JDBC连接的参数,从而告诉Hibernate如何访问数据库;还可以设置Hibernate框架的运行时行为;最后给出持久化实体类与数据库表之间映射的文件。
2)创建持久化类(PO)持久化类(实体类)是系统中的实体对象的抽象,与数据库表之间存在一定的对应关系。
3)创建持久化类与数据库表之间的映射文件:*.hbm.xml对象和数据库表之间的映射可以通过一个XML文档来定义,该文件名往往与类名相同。
除了使用映射文件来表达这种映射关系,还可以使用Java Annotation(注解),后者是Hibernate4建议使用的方式。
4)通过Hibernate框架API编程着重理解Configuration、SessionFactory、Session、Transaction、Query等类的使用。
12.3 开发基于Hibernate的Java应用程序1.创建一个Java项目本例将完成一个关于产品数据的访问程序。
在Eclipse中信建一个Java Project,项目名称为“HibernateDemo”,如图12.2所示,点击“Finish”完成创建即可。
J2EE实验报告学号姓名班级上课地点教师上课时间实验六熟悉hibernate框架1. 实验目的1.1.掌握hibernate框架搭建步骤;2. 实验环境2.1 MyEclipse2.2 Window XP2.3 MySQL4. 教师批改意见成绩签字:日期:实验内容1功能描述搭建hibernate框架,熟悉hibernate框架搭建步骤。
并编写一个测试代码,实现简单的业务处理。
2实验步骤2.1 搭建hibernate框架(0) 新建web project项目,项目名称自定义(我取名为EX_Hibernate);(1) 将hibernate需要的jar包拷贝到lib下;2.2 新建bean类在src下新增包.xmut.bean(bean必须,前缀包路径可自定义),在该包下新建类News.java:package .xmut.bean;public class News {private int id;private String title;private String content;//省略get set 方法}2.3 新建bean.hbm.xml文件在News.java 同一目录下,新建News.hbm.xml文件<?xml version="1.0"encoding="utf-8"?><!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN""/hibernate-mapping-3.0.dtd"> <hibernate-mapping><class name=".xmut.bean.News"table="table1"> <id name="id"type="integer"><column name="id"/><generator class="native"/></id><property name="title"type="ng.String"><column name="title"length="10"/></property><property name="content"type="ng.String"><column name="content"length="10"></column></property></class></hibernate-mapping>2.4 新建hibernate.cfg.xml文件在src下新建hibernate.cfg.xml文件<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""/dtd/hibernate-configuration-3.0.d td"><hibernate-configuration><!-- 配置session节点 --><session-factory name="foo"><!-- 配置连接数据库信息 : user password url driver_class --><property name="ername">root</property><property name="connection.password">1234</property><propertyname="connection.url">jdbc:mysql://127.0.0.1:3306/bag</propert y><propertyname="connection.driver_class">com.mysql.jdbc.Driver</property ><!-- 配置数据库方言 --><propertyname="dialect">org.hibernate.dialect.MySQLDialect</property><!-- 配置进行数据库操作时,是否需要显示sql语句 --><property name="show_sql">true</property><!-- 配置如何通过反射生成数据表 --><property name="hbm2ddl.auto">create</property><!-- 关联 hibernate 映射文件 --><mapping resource="cn/edu/xmut/bean/News.hbm.xml"/> </session-factory></hibernate-configuration>运行结果:对应的bag数据库中出现对应的table1表以及表中相应的数据。
Oracle应用开发综合实验报告题目:综合实验Hibernate技术应用指导教师:王岩姓名:常智棋班级学号:10301125成绩:日期:2012.12.09实验题目:综合实验Hibernate技术应用一.预习内容Hibernate是对JDBC的轻量级封装,因此在很多情况下Hibernate的性能比直接使用JDBC存取数据库要低。
然而,通过正确的方法和策略,在使用Hibernate的时候还是可以非常接近直接使用JDBC时的效率的,并且,在有些情况下还有可能高于使用JDBC时的执行效率。
在进行Hibernate性能优化时,需要从以下几个方面进行考虑:数据库设计调整。
HQL优化。
API的正确使用(如根据不同的业务类型选用不同的集合及查询API)。
主配置参数(日志、查询缓存、fetch_size、batch_size等)。
映射文件优化(ID生成策略、二级缓存、延迟加载、关联优化)。
一级缓存的管理。
针对二级缓存,还有许多特有的策略。
事务控制策略。
数据的查询性能往往是影响一个应用系统性能的主要因素。
对查询性能的影响会涉及到系统软件开发的各个阶段,例如,良好的设计、正确的查询方法、适当的缓存都有利于系统性能的提升。
系统性能的提升设计到系统中的各个方面,是一个相互平衡的过程,需要在应用的各个阶段都要考虑。
并且在开发、运行的过程中要不断地调整和优化才能逐步提升系统的性能。
二.实验目的与要求1.了解软件分层体系结构2.理解持久化层3.了解软件的模型4.理解对象的关系5.理解ORM及Hibernate原理6.掌握Hibernate的基本配置及映射7.掌握建立和使用Session执行持久化操作8.理解Session的线程安全9.Hibernate回调和拦截1、建立表orders:用于存储订单列表信息;表order_items:用于存储单个订单的详细信息。
其结构分别为:表1 orders表结构字段名字段类型字段宽度说明id NUMBER 20 订单编号(主键)order_date Date 订单日期(非空)user_name VARCHAR2 10 客户名称(非空)city VARCHAR2 20 客户所在城市(默认沈阳)表2 order_items表结构字段名字段类型字段宽度说明order_id NUMBER 20 订单编号(主键)VARCHAR2 20 产品名称(非空)product_NAMEquantity NUMBER 4 数量(大于0,小于100)unit_price NUMBER (10,2) 产品单价2、创建数据库连接程序,能够对表orders进行增、删、改和查。
实验4Hibernate基础应用1 实验目的:1 通过实例开发,熟练掌握Hibernate的开发过程。
2 掌握Hibernate对数据表的映射及相关配置文件的配置。
2 实验内容:对学生表student表进行增、删、改、查操作。
熟练掌握Hibernate持久层对数据表的映射关系。
3 实验程序package org.test;import java.util.List;import org.hibernate.Query;import org.hibernate.Session;import org.hibernate.Transaction;import org.vo.Student;import org.util.HibernateSessionFactory;public class Test {public Session session;public static void main(String[] args) {Test ht=new Test(); //创建类对象ht.getCurrentSession(); //获得session对象ht.saveUser(); //插入一条记录System.out.println("增加一条记录后结果======");ht.queryUser(); //查看数据库结果ht.updateUser(); //修改该条记录System.out.println("修改该条记录后结果======");ht.queryUser(); //查看数据库结果ht.deleteUser(); //删除该条记录System.out.println("删除该条记录后结果======");ht.queryUser(); //查看数据库结果ht.closeSession(); //关闭session }//获得session方法public void getCurrentSession(){//调用HibernateSessionFactory 的getSession 方法创建Session 对象session = HibernateSessionFactory.getSession();}//关闭session方法public void closeSession(){if(session!=null){HibernateSessionFactory.closeSession(); // 关闭Session }}//插入一条记录方法public void saveUser(){Transaction t1 = session.beginTransaction();// 创建事务对象Student user = new Student();user.setId(4);user.setSno("1205");user.setName("赵雪飞");user.setClass_("17341");user.setGrade(85);session.save(user);mit(); // 提交事务}//修改这条记录方法public void updateUser(){Transaction t2 = session.beginTransaction();//get方法的第二个参数是表中主键id的实际值Student user = (Student)session.get(Student.class,new Integer(2));user.setGrade(80);session.update(user);mit();}//查询数据库结果方法public void queryUser(){try{Query query = session.createQuery("from Student");List list=query.list();for(int i=0;i<list.size();i++){Student user = (Student)list.get(i);System.out.println(user.getId());System.out.println(user.getSno());System.out.println(user.getName());System.out.println(user.getClass_());System.out.println(user.getGrade());}}catch(Exception e){e.printStackTrace();}}//删除该条记录方法public void deleteUser(){Transaction t3 = session.beginTransaction();Student user = (Student)session.get(Student.class, new Integer(3));session.delete(user);mit();}}4 实验结果5 实验小结学了Struts框架,主要是用于图形界面的交互,今天学了Hibernate框架,主要是用于对数据库的操作,感觉功能很强大,两者如果结合,想必作用应该非常很轻大。
实验五Hibernate、Spring及SSH集成实验内容学习Hibernate、Spring应用的基本开发,及SSH的简单集成实验目的了解Hibernate、Spring框架的机制掌握Hibernate、Spring应用的配置掌握Spring中Bean注解扫描装配掌握Hibernate基本编程掌握SSH的简单集成环境要求服务器:Tomcat6.0或更高,jboss6或更高集成开发环境:MyEclipse 8.6 或更高实验指导1.Hibernate简单使用1)创建表在MySQL数据库服务器上的test中创建student表,字段如下:字段名类型说明id Integer 自增,主键xh varchar(10)name varchar(10)sex varchar(2)className varchar(16)2)创建数据库连接通过菜单“window”->“show view”打开“DB Browser”窗口,在该窗口中点击右键,在弹出菜单总选择“New”,打开如下窗口。
在“Driver template”中选择“MySQL”,“Driver name”中输入一个名称(mysql),修改“Connection URL”为:jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8,输入数据库的用户名和口令,点击“Add JARS”按钮添加Mysql的驱动Jar包,点击“Finish”按钮完成创建。
3)创建工程及添加Hiberbate支持创建一个Java工程,名称为hh。
在左侧“package explore”窗口的“hh”工程名上点击右键,在弹出的菜单中选择“MyEclipse”->“Add Hibernate Capapilities...”,弹出如下对话框:在本对话框中选择我们需要的Hibernate的Jar包,使用默认选择即可,点击“Next”按钮,弹出如下窗口:在本对话框中用于指定Hibernate的配置文件的位置及名称,使用默认即可。
第十章Hibernate框架中的缓存技术(第2/2部分)1.1在网上商城项目中应用Hibernate缓存技术1.1.1应用Hibernate框架二级缓存技术1、在DAO组件中启用Hibernate框架中的二级缓存技术(1)需要在hibernate.cfg.xml中增加一个属性项目(以EHCache为例)<property name = "hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider </property>其它的配置项目请见图10.8所示。
图10.8 在hibernate.cfg.xml中增加一个属性项目这样在Hibernate框架启动时,将会在控制台中出现下面的图10.9所示的状态提示图10.9 在控制台中出现的启动状态提示(2)在ehcache.xml文件中再针对Cache实现本身进行配置ehcache.xml的缓存配置文件应该和hibernate.cfg.xml文件放在一起的(默认的位置在classpath,可以放到应用系统的WEB-INF/classes的目录下)。
对于该ehcache.xml 的缓存配置文件,实际可以从Hibernate框架的系统包目录中的etc目录中获得其模板配置文件。
请见图10.10所示。
图10.10 Hibernate的系统包的etc目录中获得ehcache.xml模板配置文件(3)在本项目中新增加一个ehcache.xml的配置文件右击项目名称,选择【新建】菜单,再选择【文件】菜单项,将出现下面的图10.11所示的对话框。
在对话框的名称栏中输入文件名称为ehcache.xml。
请见下面的图图10.11所示。
图10.11 新增加一个ehcache.xml的配置文件(4)设计ehcache.xml文件的内容【例10-9】ehcache.xml文件的内容示例<?xml version="1.0" encoding="UTF-8" ?><ehcache><diskStore path="java.io.tmpdir"/><defaultCache maxElementsInMemory="1000" eternal="false"timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"/><cache name="erInfoPO"maxElementsInMemory="500" eternal="false" overflowToDisk="true"timeToLiveSeconds="7200" timeToIdleSeconds="3600" /><cache name="contactMethod" maxElementsInMemory="500"eternal="false" timeToLiveSeconds="7200"timeToIdleSeconds="3600" overflowToDisk="true" /><cache name="com.px1987.webshop.dao.pobject.AdminUserInfoPO"maxElementsInMemory="500" eternal="false" overflowToDisk="true"timeToLiveSeconds="7200" timeToIdleSeconds="3600" /><cache name="com.px1987.webshop.dao.pobject.GoodsInfoPO"maxElementsInMemory="500" eternal="false" timeToLiveSeconds="7200"timeToIdleSeconds="3600" overflowToDisk="true" /><cache name="com.px1987.webshop.dao.pobject.OrderInfoPO"maxElementsInMemory="500" eternal="false" timeToLiveSeconds="7200"timeToIdleSeconds="3600" overflowToDisk="true" /></ehcache>注意:在上面的ehcache.xml文件中,为项目中的各个持久类提供了一个缓存策略的定义。
hibernate createnativequery 使用Hibernate CreateNativeQuery 使用指导Hibernate是一个流行的Java持久化框架,它提供了一种方便的方式来将对象模型映射到关系数据库中。
除了支持HQL(Hibernate Query Language)查询,Hibernate还允许开发人员直接执行原生的SQL查询。
这对于在特定情况下需要执行复杂查询或优化性能时非常有用。
本文将介绍Hibernate的CreateNativeQuery方法的使用,一步一步地回答常见的问题。
什么是CreateNativeQuery?CreateNativeQuery是Hibernate的一个方法,它允许开发人员执行原生的SQL查询。
它接受一个SQL查询字符串作为参数,并返回一个NativeQuery对象,可以使用该对象来执行查询并获取结果。
如何使用CreateNativeQuery?以下是使用CreateNativeQuery的基本步骤:步骤1: 获取Hibernate Session要执行SQL查询,首先需要通过Hibernate获取一个Session对象。
Session是Hibernate的核心接口之一,它表示与数据库的连接和数据读写操作。
例子:javaSession session = HibernateSessionFactory.getSession();步骤2: 创建原生SQL查询使用session对象的CreateNativeQuery方法来创建一个NativeQuery 对象。
该方法接受一个SQL查询字符串作为参数。
例子:javaString sql = "SELECT * FROM users WHERE age > :age"; NativeQuery<User> query = session.createNativeQuery(sql, User.class);在上面的例子中,我们创建了一个查询,用于选择年龄大于给定参数age的用户。
实验3Hibernate使用基础一、实验目的1.理解Hibernate的基本概念与作用2.掌握Hibernate体系结构、核心接口及其对象状态和对象特征3.熟悉利用MyEclipse2014进行Hibernate应用开发的基本步骤;4.了解Hibernate对象关系映射5.掌握事务管理的基本方法。
二、实验步骤1.建立数据库及表利用MySQLInstance建立MySQL数据库,数据库名为:hibernatedb,并在其中建立表,表名为:students。
SQL命令如下:CREATE DATABASE `hibernated ;CREATE TABLE `students` (`sid` int(11) NOT NULL,`sname` varchar(45) DEFAULT NULL,PRIMARY KEY (`sid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;2.在MyEclipse 2014中建立MySQL数据库连接驱动Hibernate2(1)启动MyEclipse 2014,选择Windows→OpenPerspective→MyEclipse DatabaseExplorer(2)在MyEclipse Database Explorer中,在左侧窗格中右击鼠标,在快捷菜单中选择New命令,如图6.10所示。
(3)在弹出编辑数据库连接驱动对话框中,编辑如下内容:DriveName:Hibernate2ConnectionURL:jdbc:mysql://localhost:3306/hibernatedbUser Name: rootPassword: 123456单击Add JARs添加Drive JARs:mysql-connector-java-5.1.13-bin(4)勾选SavePassword,单击TestDriver,测试成功后单击Finish。
Hibernate 实验指导1环境配置JDK 5.0Eclipse 3.3MyEclipse 6.1GA数据库MySQL 5.0数据库客户端MySQL-FrontMySQL JDBC驱动mysql-connector-java-3.1.13-bin.jar2第一个Hibernate示例构建一个Hibernate项目主要分为以下几个步骤:创建数据库创建支持Hibernate的Java project构建Hibernate基础代码日志器配置编写测试类2.1 创建数据库创建名为“hibernate_db”的数据库,以及库表t_user,t_user表中包含以下字段:●自增主键“id”●用户名字段“name”●生日字段“birthday”●Email字段“email”●性别字段“sex”构建脚本如下:在MySQL-Front中刷新后可以看到创建的数据库和库表:2.2 创建支持Hibernate的Java project打开Eclipse,创建Java project:将MySQL JDBC驱动copy到lib目录下,然后将其纳入项目的构建路径(build path):选中HibernateSample project,增加Hibernate支持:Next,保留默认值:Next:Next,取消“Create SessionFactory class”选项:在hibernate.cfg.xml的编辑界面中增加hibernate属性配置:查看hibernate配置文件的源码(调整顺序并增加注释):2.3 构建Hibernate基础代码Hibernate基础代码包括POJO(Plain Old Java Object)类,也称为实体类和Hibernate映射文件。
与t_user表对应的实体类为User:User类体现的是ORM中的O(Object),即对“用户”实体对象的封装,包含了用户的两个属性。
t_user是关系型(Ralational)数据库表,Hibernate使用映射文件将实体对象(Object)和关系型数据(Ralational)相关联,在Hibernate 中,映射文件通常以“.hbm.xml”作为后缀。
实验二使用hibernate实现关系映射1、实验目的(1) 理解什么是单向、双向、多对一、一对多的含义(2) 掌握action类的设计与实现2、实验设备与环境硬件:安装有Windows XP/7/8系统的微机一台。
软件:JDK1.6以上、MyEclipse 8.0以上,oracle9i以上。
3、实验内容(1) 使用hibernate配置文件创建学生信息表(学号、姓名、性别、出生日期、班级)、班级信息表(班级编号、班级名称、开班日期)。
(2) 使用hibernate完成两表的主外键关联。
(3) 将配置文件配置成单向多对一,完成对班级和学生信息的增删改查。
(4) 将配置文件配置成双向一对多,完成学生的增删改查。
班级的增、删。
4、实验要求(1) 实验前书写预习报告,包括类图和方法的代码描述。
(2) 记录程序调试中出现的问题和解决方法。
(3) 实验后必须按照要求独立完成实验报告。
(4) 打印源程序清单和测试结果附在实验报告的后面。
5、实验提示(1) 创建web 项目(也可以是java项目)hb1.(2) 将制定jar包导入到工程项目中。
包括:antlr-2.7.6.jarcommons-collections-3.1.jarcommons-logging-1.1.1.jardom4j-1.6.1.jarhibernate3.jarjavassist-3.4.GA.jarjta-1.1.jarlog4j-1.2.14.jarmsbase.jarslf4j-api-1.5.6.jarslf4j-log4j12-1.5.6.jarsqljdbc4.jar(3) 在src下创建制定名为:hibernate.cfg.xml的文件作为hibernate配置文件。
(4) src 下创建包com.hb.entity ,并创建班级信息、学生信息的实体类。
(5) 为相关实体类创建orm文件,并引入到配置文件中去(6) Student和Classinfo 两个类关系为例,进行多对一实体映射关联。
毕业设计(论文)外文资料原文及译文专业计算机科学与技术班级学号姓名指导教师原文出处:Hibernate in ActionHibernate In ActionCHRISTIAN BAUERGAVIN KINGRetrieving objectsRetrieving persistent objects from the database is one of the most interesting (andcomplex) parts of working with Hibernate. Hibernate provides the following waysto get objects out of the database: ■Navigating the object graph, starting from an already loaded object, byaccessing the associated objects through property accessor methods such as a User.getAddress().getCity(). Hibernate will automatically load (or preload)nodes of the graph while you navigate the graph if the Session is open.■ Retrieving by identifier, which is the most convenient and performant method when the uniqueidentifier value of an object is known.■ Using the Hibernate Query Language (HQL), which is a fullobject-orientedquerylanguage.■ Using the, Hibernate Criteria API, which provides a type-safe and objectoriented way to perform queries without the need for string manipulation.This facility includes queries based on an example object.■ Using native SQL queries, where Hibernate takes care of mapping the JDBC result sets to graphs of persistent objects.In yo ur Hibernate applications, you’ll use a combination of these techniques.Each retrieval method may use a different fetching strategy—that is, a strategy that defines what part of the persistent object graph should be retrieved. The goal is to find the best retrieval method and fetching strategy for every use case in your application while at the same time minimizing the number of SQL queries for best performance. We won’t discuss each retrieval method in much detail in this section; instead we’ll fo cus on the basic fetching strategies and how to tune Hibernate mapping files for best default fetching for all methods. Before we look at the fetching strategies, we’ll give an overview of the retrieval methods. (We mention the Hibernate caching system but fully explore it in the next chapter.) Let’s start with the simplest case, retrieval of an object by giving its identifier value (navigatingthe object graph should self-explanatory). You saw a simple retrieval by identifier earlier in this chapter, but there is more to know about it.Retrieving objects by identifierThe following Hibernate code snippet retrieves a User object from the database:User user = (User) session.get(User.class, userID);The get() method is special because the identifier uniquely identifies a single;instance of a class. Hence it’s common for applications to use the identifier as aconvenient handle to a persistent object. Retrieval by identifier can use the cachewhen retrieving an object, avoiding a database hit if the object is already cached.Hibernate also provides a load() method:User user = (User) session.load(User.class, userID);The load() method is older; get() was added to Hibernate’s API due to userrequest. The difference is trivial:■ If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returnsnull if the object can’t be found.■ The load() method may return a proxy instead of a real persistent instance.A proxy is a placeholder that triggers the loadin g of the real object when it’s accessed for the first time; we discuss proxies later in this section. On the other hand, get() never returns a proxy.Choosing between get() and load() is easy: If you’re certain the persistentobject exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed.Of course, retrieving an object by identifier isn’t as flexible as using arbitrary queries.Introducing HQLThe Hibernate Query Language is an object-oriented dialect of the familiar relational query languageSQL. HQL bears close resemblances to ODMG OQL andEJB-QL; but unlike OQL, it’s adapted for use withSQL databases, and it’s much more powerful and elegant than EJB-QL (However, EJB-QL 3.0 will be verysimilar to HQL.) HQL is easy to learn with basic knowledge of SQL. HQL isn’t a data-manipulationlanguage like SQL. It’s used only for object retrieval, not for updating, inserting, or deleting data. Objectstate synchronization is the job of the persistence manager, not the developer.Most of the time, you’ll only n eed to retrieve objects of a particular class and restrict by the properties of that class. For example, the following query retrieves a user by first name:Query q = session.createQuery("from User u where u.firstname = :fname");q.setString("fname", "Max");List result = q.list();After preparing query q, we bind the identifier value to a named parameter, fname.The result is returned as a List of User objects.HQL is powerful, and even though you may not use the advanced features all the time, you’ll need them for some difficult problems. For example, HQL supports the following:■ The ability to apply restrictions to properties of associated objects related by reference or held in collections (to navigate the object graph using query language).■ The ability to retrieve only properties of an entity or entities, without the overhead of loading the entity itself in a transactional scope. This is sometimes called a report query; it’s more correctly called projection.■ The ability to order the results of the query.■ The ability to paginate the results.■ Aggregation with group by, having, and aggregate functions like sum, min,and max.■ Outer joins when retrieving multiple objects per row.■ The ability to call user-defined SQL functions.■ Subqueries (nested queries).We discuss all these features in chapter 7, together with the optional native SQL query mechanism.Query by criteriaThe Hibernate query by criteria (QBC) API lets you build a query by manipulating criteria objects at runtime. This approach lets you specify constraints dynamically without direct string manipulations, but it doesn’t lose much of the flexibility or power of HQL. On the other hand, queries expressed as criteria are often less readable than queries expressed in HQL.Retrieving a user by first name is easy using a Criteria object:Criteria criteria = session.createCriteria(User.class);criteria.add( Expression.like("firstname", "Max") );List result = criteria.list();A Criteria is a tree of Criterion instances. The Expression class provides static factory methods that return Criterion instances. Once the desired criteria tree is built, it’s executed against the database.Many developers prefer QBC, considering it a more object-oriented approach. They also like the fact that the query syntax may be parsed and validated at compile time, whereas HQL expressions aren’t parsed until runtime.The nice thing about the Hibernate Criteria API is the Criterion framework.This framework allows extension by the user, which is difficult in the case of a querylanguage like HQL.Query by exampleAs part of the QBC facility, Hibernate supports query by example (QBE). The idea behind QBE is that the application supplies an instance of the queried class with certain property values set (to nondefault values). The query returns all persistent instances with matching property values. QBE isn’t a particularly powerful approach, but it can be convenient for some applications. The following code snippet demonstrates a Hibernate QBE:User exampleUser = new User();exampleUser.setFirstname("Max");Criteria criteria = session.createCriteria(User.class);criteria.add( Example.create(exampleUser) );List result = criteria.list();A typical use case for QBE is a search screen that allows users to specify a range of property values to be matched by the returned result set. This kind of functionality can be difficult to express cleanly in a query language; string manipulations would be required to specify a dynamic set of constraints.Both the QBC API and the example query mechanism are discussed in more detail in chapter 7.You now know the basic retrieval options in Hibernate. We focus on the strategies for fetching object graphs in the rest of this section. A fetching strategy defines what part of the object graph (or, what subgraph) is retrieved with a query or load operation.Fetching strategiesIn traditional relational data access, you’d fetch all the data required for a particular with a single SQL query, taking advantage of inner and outer joins to retrieve related entities. Some primitive ORM implementations fetch data piecemeal, with many requests for small chunks of data in response to the application’s navigating a graph of persistent objects. This approach doesn’t make efficient use of the relationa l database’s join capabilities. In fact, this data access strategy scales poorly by nature. One of the most difficult problems in ORM—probably the most difficult—is providing for efficient access to relational data, given an application that prefers to treat the data as a graph of objects.For the kinds of applications we’ve often worked with (multi-user, distributed, web, and enterprise applications), object retrieval using many round trips to/from the database is unacceptable. Hence we argue that tools should emphasize the R inORM to a much greater extent than has been traditional.The problem of fetching object graphs efficiently (with minimal access to the database) has often been addressed by providing association-level fetching strategies specified in metadata of the association mapping. The trouble with this approach is that each piece of code that uses an entity requires a different set of associated objects. But this isn’t enough. We argue that what is needed is support for fine-grained runtime association fetching strategies. Hibernate supports both, it lets you specify a default fetching strategy in the mapping file and then override it at runtime in code.Hibernate allows you to choose among four fetching strategies for any association, in association metadata and at runtime:■ Immediate fetching—The associated object is fetched immediately, using a sequential database read (or cache lookup).■ Lazy fetching—The associated object or collection is fetched “lazily,” when it’s first accessed. This results in a new request to the database (unless the associated object is cached).■ Eager fetching—The associated object or collection is fetched together with the owning object, using an SQL outer join, and no further database request is required.■ Batch fetching—This approach may be used to improve the performance of lazy fetching by retrieving a batch of objects or collections when a lazy association is accessed. (Batch fetching may also be used to improve the performance of immediate fetching.)Let’s look more closely at each fetchin g strategy.Immediate fetchingImmediate association fetching occurs when you retrieve an entity from the database and then retrieve another associated entity or entities in a further request to the database or cache. Immediate fetching isn’t usually an efficient fetching strategy unless you expect the associated entities to almost always be cached already.Lazy fetchingWhen a client requests an entity and its associated graph of objects from the database, it isn’t usually necessary to retrieve the whole g raph of every (indirectly) associated object. You wouldn’t want to load the whole database into memory at once; for example, loading a single Category shouldn’t trigger the loading of all Items in that category.Lazy fetching lets you decide how much of the object graph is loaded in the first database hit and which associations should be loaded only when they’re first accessed. Lazy fetching is a foundational concept in object persistence and the first step to attaining acceptable performance.We recommend that, to start with, all associations be configured for lazy (or perhaps batched lazy) fetching in the mapping file. This strategy may then be overridden at runtime by queries that force eager fetching to occur.Eager (outer join) fetchingLazy association fetching can help reduce database load and is often a good default strategy. However, it’s a bit like a blind guess as far as performance optimization goes.Eager fetching lets you explicitly specify which associated objects should be loaded together with the referencing object. Hibernate can then return the associated objects in a single database request, utilizing an SQL OUTER JOIN. Performance optimization in Hibernate often involves judicious use of eager fetching for particular transactions. Hence, even though default eager fetching may be declared in the mapping file, it’s more common to specify the use of this strategy at runtime for a particular HQL or criteria query.Batch fetchingBatch fetching isn’t strictly an association fetching strategy; it’s a technique that may help improve the performance of lazy (or immediate) fetching. Usually, when you load an object or collection, your SQL WHERE clause specifies the identifier of the object or object that owns the collection. If batch fetching is enabled, Hibernate looks to see what other proxied instances or uninitialized collections are referencedin the current session and tries to load them at the same time by specifying multiple identifier values in the WHERE clause.We aren’t great fans of this ap proach; eager fetching is almost always faster. Batch fetching is useful for inexperienced users who wish to achieve acceptable performance in Hibernate without having to think too hard about the SQL that will be executed. (Note that batch fetching may be familiar to you, since it’s used by many EJB2 engines.)We’ll now declare the fetching strategy for some associations in our mapping metadata.译文:Hibernate的实践与应用Hibernate In ActionCHRISTIAN BAUERGAVIN KING检索对象从数据库中检索对象是使用Hibernate最有趣(也是最复杂)的部分。
Hibernate 实验指导1环境配置JDK 5.0Eclipse 3.3MyEclipse 6.1GA数据库MySQL 5.0数据库客户端MySQL-FrontMySQL JDBC驱动mysql-connector-java-3.1.13-bin.jar2第一个Hibernate示例构建一个Hibernate项目主要分为以下几个步骤:创建数据库创建支持Hibernate的Java project构建Hibernate基础代码日志器配置编写测试类2.1 创建数据库创建名为“hibernate_db”的数据库,以及库表user,t_user表中包含以下字段:●自增主键“id”●用户名字段“name”●生日字段“birthday”●Email字段“email”●性别字段“sex”构建脚本如下:CREATE DATABASE hibernate_db;USE hibernate_db;CREATE TABLE t_user (id int(11) NOT NULL auto_increment,name varchar(20) default NULL,birthday date NULL default NULL,email varchar(100) default NULL,sex char(1) default NULL,PRIMARY KEY (id));在MySQL-Front中刷新后可以看到创建的数据库和库表:2.2 创建支持Hibernate的Java project打开Eclipse,创建Java project:将MySQL JDBC驱动copy到lib目录下,然后将其纳入项目的构建路径(build path):选中HibernateSample project,增加Hibernate支持:点击Next,保留默认值:点击Next:Next,取消“Create SessionFactory class”选项:然后Finish。
在hibernate.cfg.xml的编辑界面中增加hibernate属性配置:查看hibernate配置文件的源码(调整顺序并增加注释):2.3 生成数据库表对应的Java数据对象和映射文件,构建Hibernate基础代码Hibernate基础代码包括POJO(Plain Old Java Object)类,也称为实体类和Hibernate映射文件。
首先在MyEclispse下创建一个名为com.witbridge.hibernate.helloworld的包,这个包将用来存放与数据库表格对应的Java类User。
从主菜单栏,选中Windows Open Perspective Other MyEclipse Database Explorer,打开MyEclipse Database Explorer视图。
打开前面创建的mysql数据连接,选中数据库表t_user,右击,选择菜单Hibernate Reverse Engineering…,将启动Hibernate Reverse Engineering向导,生成实体类为User。
点击Next点击Next点击Finish,自动生成与t_user表对应的实体类为User。
User类体现的是ORM中的O(Object),即对“用户”实体对象的封装,包含了用户的两个属性。
t_user是关系型(Ralational)数据库表,Hibernate使用映射文件将实体对象(Object)和关系型数据(Ralational)相关联,在Hibernate 中,映射文件通常以“.hbm.xml”作为后缀。
下面编写映射文件内容(注意t_user表中的email和sex字段并没有映射,也就是说Hibernate并不处理这两个字段):将映射文件加载到Hibernate配置文件hibernate.cfg.xml中:2.4 日志器配置Hibernate采用Apache common logging,并使用Apache log4j作为日志器的实现组件。
为了在开发过程中能够看到Hibernate框架输出的信息,我们在src 目录下增加log4j的配置文件,文件名为log4j.properties:2.5 编写测试类使用JUnit创建测试类,首先在包com.witbridge.hibernate中创建测试基类BaseTestCase:类设为abstract,并加入公共代码:创建Hibernate测试类HibernateTest:编写插入数据库的测试方法testCreate:运行测试类:在JUnit视图中看到绿条(green bar)说明测试成功,如果看到红条(red bar)说明测试失败。
在Console视图中可以看到Hibernate生成的sql语句:在MySQL-Front中刷新,查看是否已经插入记录:添加查询测试方法testRetrieve:JUnit自动运行所有以@org.junit.Test注解的方法,当一个测试类中的方法很多时,可以选择地运行某些测试方法,将不需要运行的方式增加@org.junit.Ignore:运行测试类,查看Hibernate生成的sql语句。
添加更新的测试方法testUpdate:运行测试类,查看Hibernate生成的sql语句,并观察数据库中的记录是否被修改。
增加删除的测试方法testDelete:如果所有的测试方法都测试通过(出现green bar),那么congratulations,你已经步入了Hibernate殿堂!Hibernate关联关系映射介绍及其相应的应用示例Hibernate关联关系映射目录│├─单向关联│├─一对一外键单向关联│├─一对一主键单向关联│├─一对一连接表单向关联│├─一对多外键单向关联│├─一对多连接表单向关联│├─多对一外键单向关联│├─多对一连接表单向关联│└─多对多单向关联└─双向关联├─一对一外键双向关联├─一对一主键双向关联├─一对一连接表双向关联├─一对多外键双向关联├─一对多连接表双向关联└─多对多双向关联本系列实例的开发环境:Windows XP Professional 简体中文版MySQL 5.0.45Hibernate 3.12Java SDK 1.5.06系列实例中所用的Hibernate配置文件如下:<?xml version='1.0' encoding='gb2312'?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""[url]/hibernate-configuration-3.0.dtd[/url]"><hibernate-configuration><session-factory><!--指定连接数据库驱动--><property name="connection.driver_class">com.mysql.jdbc.Driver</property><!--指定连接数据库的url,hibernate连接的数据库名--><property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate_db </property><!--指定连接数据库的用户名--><property name="ername">root</property><!--指定连接数据库的用户密码--><property name="connection.password">admin</property><!--指定连接池的大小--><property name="connection.pool_size">5</property><!--指定数据库的方言--><property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--根据需要自动创建数据库,测试环境用--><property name="hbm2ddl.auto">create</property><!--在控制台显示执行的SQL语句--><property name="show_sql">true</property><!-- Enable Hibernate's automatic session context management --><property name="current_session_context_class">thread</property><!--映射文件列表--><!--单向关联--><mapping resource="com/hdxx/dx/_n_1_fk/Addressn1fk.hbm.xml"/><mapping resource="com/hdxx/dx/_n_1_fk/Personn1fk.hbm.xml"/><mapping resource="com/hdxx/dx/_n_1_tab/Addressn1tab.hbm.xml"/><mapping resource="com/hdxx/dx/_n_1_tab/Personn1tab.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_fk/Address11fk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_fk/Person11fk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_tab/Address11tab.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_tab/Person11tab.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_pk/Address11pk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_1_pk/Person11pk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_n_fk/Address1nfk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_n_fk/Person1nfk.hbm.xml"/><mapping resource="com/hdxx/dx/_1_n_tab/Address1ntab.hbm.xml"/><mapping resource="com/hdxx/dx/_1_n_tab/Person1ntab.hbm.xml"/><mapping resource="com/hdxx/dx/_n_n/Addressnn.hbm.xml"/><mapping resource="com/hdxx/dx/_n_n/Personnn.hbm.xml"/><!--双向关联--><mapping resource="com/hdxx/sx/_1_n_fk/Address1nfk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_n_fk/Person1nfk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_n_tab/Address1ntab_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_n_tab/Person1ntab_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_n_n/Addressnn_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_n_n/Personnn_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_fk/Address11fk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_fk/Person11fk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_pk/Address11pk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_pk/Person11pk_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_tab/Address11tab_sx.hbm.xml"/><mapping resource="com/hdxx/sx/_1_1_tab/Person11tab_sx.hbm.xml"/> </session-factory></hibernate-configuration>系列实例中所用到Session工厂是:package com.hdxx.util;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static final SessionFactory sessionFactory;static {try {// Create the SessionFactory from hibernate.cfg.xmlsessionFactory = new Configuration().configure().buildSessionFactory();} catch (Throwable ex) {// Make sure you log the exception, as it might be swallowedSystem.err.println("初始化SessionFactory失败!" + ex);throw new ExceptionInInitializerError(ex);}}public static final ThreadLocal session = new ThreadLocal();public static Session getCurrentSession() throws HibernateException {Session s = (Session) session.get();//当原Session为空或已关闭时,打开一个新的Sessionif (s == null || !s.isOpen()) {s = sessionFactory.openSession();session.set(s);}return s;}public static void closeSession() throws HibernateException {Session s = (Session) session.get();session.set(null);if (s != null) {s.close();}}}Hibernate关联关系映射介绍及其相应的应用示例(注意:示例代码未含package包名称和import相关的类包。