跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc

上传人:数据九部 文档编号:10366185 上传时间:2021-05-12 格式:DOC 页数:26 大小:708KB
返回 下载 相关 举报
跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc_第1页
第1页 / 共26页
跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc_第2页
第2页 / 共26页
跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc_第3页
第3页 / 共26页
跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc_第4页
第4页 / 共26页
跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc_第5页
第5页 / 共26页
点击查看更多>>
资源描述

《跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc》由会员分享,可在线阅读,更多相关《跟我学Hibernate框架技术——在Web应用中实现“一对一”的关联(MySQL)——第2部分.doc(26页珍藏版)》请在三一文库上搜索。

1、杨教授工作室 精心创作的优秀程序员 职业提升必读系列资料目 录1.1在Web应用中实现“一对一”的关联(MySQL)第2部分21.1.1为应用系统提供一个ThreadLocal形式的Session 管理方案21.1.2对示例项目采用JUnit单元测试111.1.3再添加一个对 DAO组件的测试用例171.1.4采用C3P0连接池设定优化数据库连接201.1.5采用DBCP数据库连接池优化数据库连接221.1 在Web应用中实现“一对一”的关联(MySQL)第2部分1.1.1 为应用系统提供一个ThreadLocal形式的Session 管理方案1、新增一个HibernateUtil类2、该Hi

2、bernateUtil类的代码如下下面给出一个HibernateUtil的辅助类(来自Hibernate文档),代码如下:package com.px1987.hexample.util;import org.hibernate.*;import org.hibernate.cfg.*;public class HibernateUtil private static final SessionFactory sessionFactory; static try sessionFactory = new Configuration().configure().buildSessionFacto

3、ry();注意以配置文件和编程方式产生SessionFactory在代码上的不同之处 catch (Throwable ex) throw new ExceptionInInitializerError(ex); public static final ThreadLocal threadLocal = new ThreadLocal(); public static Session currentSession() Session currentSession = (Session) threadLocal.get(); if (currentSession = null) currentS

4、ession = sessionFactory.openSession(); threadLocal.set(currentSession); return currentSession; public static void closeSession() Session currentSession = (Session) threadLocal.get(); if (currentSession != null) currentSession.close(); threadLocal.set(null); 这个类不但在它的静态初始器中使用了SessionFactory,还使用了一个Thre

5、adLocal变量来保存Session做为当前工作线程。3、为该应用提供一个DAO接口和对应的实现类(1)添加一个DAO的接口 HibernateDAOInterface,包名称为com.px1987.hexample.dao设计该接口-应该提供什么方法(功能)package com.px1987.hexample.dao;import java.util.*;import org.hibernate.HibernateException;public interface HibernateDAOInterface public ArrayList doSelectEBookDataFromD

6、B(String selectHQL) throws HibernateException; public boolean doInsertEBookDataToDB() throws HibernateException,java.io.UnsupportedEncodingException;(2)对上面的DAO的接口提供一个实现类HibernateDAOBean,包名称为com.px1987.hexample.dao(3)代码如下package com.px1987.hexample.dao;import java.io.UnsupportedEncodingException;impo

7、rt java.util.ArrayList;import org.hibernate.HibernateException;import org.hibernate.*;import java.util.*;import mons.logging.*;import com.px1987.hexample.pobject.*;import com.px1987.hexample.util.*;public class HibernateDAOBean implements HibernateDAOInterface private static Log log = LogFactory.get

8、Log(HibernateDAOBean.class);public HibernateDAOBean() / TODO 自动生成构造函数存根public boolean doInsertEBookDataToDB() throws HibernateException,UnsupportedEncodingException Session session=null;Transaction tx=null;trysession = HibernateUtil.currentSession();/*下面的代码相当于我们执行了以下SQL语句insert into EBook (ebook_id,

9、ebookName,ebookKind,ebookPricfe) values (1, J2EE应用开发,1,7.4f) */tx= session.beginTransaction();EBook oneEBook = new EBook();/*对某些数据库系统如MSSQLServer2000必须进行字符的编码转换,否则会出现中文乱码。而对于JDTS驱动则不需要进行编码转换oneEBook.setEbookName(J2EE应用开发);*/oneEBook.setEbookName(J2EE应用开发);oneEBook.setEbookKind(1);oneEBook.setEbookPr

10、ice(7.4f);session.save(oneEBook); /保存该实体mit(); catch(HibernateException he) if ( tx!=null ) tx.rollback(); log.error(在doInsertEBookDataToDB方法中出现了HibernateException错误, he); throw he; finally /*这样我们就可以随心所欲的多次调用HibernateUtil.currentSession();,我们每次都会得到同一个当前线程的Session。不管是在我们的servlet代码中,或者在servlet filter中

11、还是在HTTP结果返回之前,我们都必须确保这个Session在你的数据库访问工作完成后关闭。*/ HibernateUtil.closeSession(); return true;public ArrayList doSelectEBookDataFromDB(String selectHQL)throws HibernateException Session session=null;Transaction tx=null;ArrayList totalEBookList =new ArrayList();trysession = HibernateUtil.currentSession(

12、);tx= session.beginTransaction();List result = session.createQuery(selectHQL).list();for (int index = 0; index result.size(); index+) EBook oneEBook = (EBook) result.get(index); totalEBookList.add(oneEBook);mit(); catch(HibernateException he) log.error(在doSelectEBookDataFromDB方法中出现了HibernateExceptio

13、n错误, he); throw he; finally HibernateUtil.closeSession(); return totalEBookList;s4、在某个Web应用中的表示层页面中使用上面的程序注意:可以在JBuilder中或者Eclipse中新增加一个Web应用,然后在该Web应用的index.jsp中添加下面的代码。%/*不带关联的测试代码*hibernateDAOBean.doInsertEBookDataToDB(); java.util.ArrayList totalEBookList= hibernateDAOBean.doSelectEBookDataFromD

14、B(from EBook); for (int index = 0; index totalEBookList.size(); index+) com.px1987.hexample.pobject.EBook oneEBook=( com.px1987.hexample.pobject.EBook)totalEBookList.get(index); out.print(EBook ID=+oneEBook.getId()+    ); out.print(EBook Name=+oneEBook.getEbookName()+  

15、  ); out.print(EBook Kind=+oneEBook.getEbookKind()+    ); out.print(EBook Price=+oneEBook.getEbookPrice()+); %5、执行该Web应用并启动tomcat(1)部署它(2)执行它http:/127.0.0.1:8080/HWebMapping/index.jsp的结果应该如下图。同时,在数据库表中将出现下面的记录另外,在状态提示中,也可以看到下面的内容1.1.2 对示例项目采用JUnit单元测试1、新建一个测试项目名称为TestHW

16、ebMapping2、将被测试项目引入到测试项目中3、添加JUnit的系统包4、添加Hibernate的系统包文件最后为下面的结果状态5、添加测试用例-对hibernate.cfg.xml中的内容进行测试package com.px1987.hexample.test;import java.io.File;import junit.framework.Assert;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;import org.

17、junit.After;import org.junit.Before;import org.junit.Test;public class TestHibernateXML Beforepublic void setUp() throws Exception Afterpublic void tearDown() throws Exception Testpublic void testHibernateXML()SessionFactory sessionFactory=null;Session oneSession=null;/根据实际改变 String hibernateXMLFile

18、=D:/HibernateExamp/HWebMapping/src/hibernate.cfg.xml;File xmlFile=new File(hibernateXMLFile);Configuration config = new Configuration().configure(xmlFile);sessionFactory=config.buildSessionFactory();Assert.assertNotNull(sessionFactory);oneSession=sessionFactory.openSession();Assert.assertNotNull(one

19、Session);6、执行该测试用例如果将配置文件设置为错误的状态,如错误的数据库名称,则出现下面的错误提示1.1.3 再添加一个对 DAO组件的测试用例1、 TestHibernateDAOBean被测试的类为com.px1987.hexample.dao.HibernateDAOBean,包名称为com.px1987.hexample.testpackage com.px1987.hexample.test;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import junit.framewor

20、k.Assert;import org.hibernate.HibernateException;import org.junit.After;import org.junit.Before;import org.junit.Test;import com.px1987.hexample.dao.HibernateDAOBean;import com.px1987.hexample.pobject.EBook;public class TestHibernateDAOBean HibernateDAOBean oneHibernateDAOBean=null;Beforepublic void

21、 setUp() throws Exception oneHibernateDAOBean=new HibernateDAOBean();Afterpublic void tearDown() throws Exception oneHibernateDAOBean=null;Testpublic void testDoInsertEBookDataToDB() throws HibernateException,UnsupportedEncodingException boolean returnResult=oneHibernateDAOBean.doInsertEBookDataToDB

22、();Assert.assertTrue(returnResult);Testpublic void testDoSelectEBookDataFromDB() String HQLSelect=from com.px1987.hexample.pobject.EBook;ArrayList resultList=oneHibernateDAOBean.doSelectEBookDataFromDB(HQLSelect);Assert.assertNotNull(resultList);for (int index = 0; index resultList.size(); index+) E

23、Book oneEBook=(EBook)resultList.get(index); Assert.assertNotNull(oneEBook);2、执行该测试用例将出现下面的结果1.1.4 采用C3P0连接池设定优化数据库连接1、添加C3P0连接池所需要的*.jar包文件c3p0-0.9.0.jar2、 在hibernate.cfg.xml文件中添加下面的内容 org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql:/localhost:3306/DataBase root root org.hibernat

24、e.connection.C3P0ConnectionProvider2051201001203 true 其中的hibernate.c3p0.acquire_increment 表示当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default为3。 1.1.5 采用DBCP数据库连接池优化数据库连接1、添加DBCP的系统包3、 修改hibernate.cfg.xml文件 org.hibernate.dialect.MySQLDialect!-由于采用DBCP提供数据库连接,因此下面的项目无用 com.mysql.jdbc.Driver jdbc:mysql:/localhost:3

25、306/DataBase root root - true 3、修改HibernateUtil类package com.px1987.hexample.util;import java.sql.Connection;import java.sql.SQLException;import mons.dbcp.BasicDataSource;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil

26、 private static final SessionFactory sessionFactory;private static final BasicDataSource oneDataSourceImple; static try sessionFactory = new Configuration().configure().buildSessionFactory(); catch (Throwable ex) throw new ExceptionInInitializerError(ex); /*下面为BasicDataSource的对象创建 * oneDataSourceImp

27、le=new BasicDataSource();oneDataSourceImple.setDriverClassName(com.mysql.jdbc.Driver);oneDataSourceImple.setUrl(jdbc:mysql:/localhost:3306/DataBase);oneDataSourceImple.setUsername(root);oneDataSourceImple.setPassword(root);oneDataSourceImple.setMaxActive(12); /最大的连接数目/oneDataSourceImple.setDefaultAu

28、toCommit(true); public static final ThreadLocal threadLocal = new ThreadLocal(); static Connection con=null; public static Session currentSession() Session currentSession = (Session) threadLocal.get(); if (currentSession = null) try con=oneDataSourceImple.getConnection(); catch (SQLException e) e.pr

29、intStackTrace(); currentSession = sessionFactory.openSession(con); threadLocal.set(currentSession); return currentSession; public static void closeSession() Session currentSession = (Session) threadLocal.get(); if (currentSession != null) try con.close(); catch (SQLException e) e.printStackTrace(); currentSession.close(); threadLocal.set(null); 4、再执行测试用例26杨教授工作室,版权所有,盗版必究, 26/26页

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 科普知识


经营许可证编号:宁ICP备18001539号-1