Hibernate创建步骤

(五大核心接口:Configuration/SessionFactory/Session/Transaction/Query)

1.新建工程,导入需要的jar包。

2.利用MyEclipse自动生成功能在工程中创建hibernate.cfg.xml配置文件和

HibernateSessionFactory.java工具类。生成的主要内容如下:

hibernate.cfg.xml:

  1. <hibernate-configuration>
  2.  
  3. <session-factory>
  4. <property name="connection.username">root</property>
  5. <property name="connection.url">
  6. jdbc:mysql://localhost:3306/databasename
  7. </property>
  8. <property name="dialect">
  9. org.hibernate.dialect.MySQLDialect
  10. </property>
  11. <property name="myeclipse.connection.profile">
  12. dangdang
  13. </property>
  14. <property name="connection.password">root</property>
  15. <property name="connection.driver_class">
  16. com.mysql.jdbc.Driver
  17. </property>
  18. <mapping resource="entity/User.hbm.xml" />
  19.  
  20. </session-factory>
  21.  
  22. </hibernate-configuration>

HibernateSessionFactory.java:

  1. package com.hibernate;
  2.  
  3. import java.sql.SQLException;
  4.  
  5. import org.hibernate.HibernateException;
  6. import org.hibernate.Session;
  7. import org.hibernate.SessionFactory;
  8. import org.hibernate.cfg.Configuration;
  9.  
  10. /**
  11. * Configures and provides access to Hibernate sessions, tied to the
  12. * current thread of execution. Follows the Thread Local Session
  13. * pattern, see {@link http://hibernate.org/42.html}.
  14. */
  15. public class HibernateSessionFactory {
  16.  
  17. /**
  18. * Location of hibernate.cfg.xml file.
  19. * NOTICE: Location should be on the classpath as Hibernate uses
  20. * #resourceAsStream style lookup for its configuration file. That
  21. * is place the config file in a Java package - the default location
  22. * is the default Java package.<br><br>
  23. * Defaults: <br>
  24. * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code>
  25. * You can change location with setConfigFile method
  26. * session will be rebuilded after change of config file
  27. */
  28. private static String CONFIG_FILE_LOCATION = "/com/hibernate/hibernate.cfg.xml";
  29. private static final ThreadLocal threadLocal = new ThreadLocal();
  30. private static Configuration configuration = new Configuration();
  31. private static SessionFactory sessionFactory;
  32. private static String configFile = CONFIG_FILE_LOCATION;
  33.  
  34. private HibernateSessionFactory() {
  35. }
  36.  
  37. /**
  38. * Returns the ThreadLocal Session instance. Lazy initialize
  39. * the <code>SessionFactory</code> if needed.
  40. *
  41. * @return Session
  42. * @throws HibernateException
  43. */
  44. public static Session getCurrentSession() throws HibernateException {
  45. Session session = (Session) threadLocal.get();
  46.  
  47. try {
  48. if (session == null || !session.isOpen()|| session.connection().isClosed()) {
  49. if (sessionFactory == null) {
  50. rebuildSessionFactory();
  51. }
  52. session = (sessionFactory != null) ? sessionFactory.openSession()
  53. : null;
  54. threadLocal.set(session);
  55. }
  56. } catch (SQLException e) {
  57. // TODO Auto-generated catch block
  58. e.printStackTrace();
  59. }
  60. return session;
  61. }
  62.  
  63. /**
  64. * Rebuild hibernate session factory
  65. *
  66. */
  67. public static void rebuildSessionFactory() {
  68. try {
  69. configuration.configure(configFile);
  70. sessionFactory = configuration.buildSessionFactory();
  71. } catch (Exception e) {
  72. System.err
  73. .println("%%%% Error Creating SessionFactory %%%%");
  74. e.printStackTrace();
  75. }
  76. }
  77.  
  78. /**
  79. * Close the single hibernate session instance.
  80. *
  81. * @throws HibernateException
  82. */
  83. public static void closeCurrentSession() throws HibernateException {
  84. Session session = (Session) threadLocal.get();
  85. threadLocal.set(null);
  86.  
  87. if (session != null) {
  88. session.close();
  89. }
  90. }
  91.  
  92. /**
  93. * return session factory
  94. *
  95. */
  96. public static SessionFactory getSessionFactory() {
  97. return sessionFactory;
  98. }
  99.  
  100. /**
  101. * return session factory
  102. *
  103. * session factory will be rebuilded in the next call
  104. */
  105. public static void setConfigFile(String configFile) {
  106. HibernateSessionFactory.configFile = configFile;
  107. sessionFactory = null;
  108. }
  109.  
  110. /**
  111. * return hibernate configuration
  112. *
  113. */
  114. public static Configuration getConfiguration() {
  115. return configuration;
  116. }
  117.  
  118. }

3.创建UserDao接口和接口的实现类UserDaoImpl,实现类中测试:

UserDaoImpl.java:

  1. public class UserDaoImpl implements UserDao {
  2.  
  3. public List<User> findAll() {
  4. Session session = HibernateSessionFactory.getSession();
  5. Transaction tx = session.beginTransaction();
  6. Query query = session.createQuery("from User");
  7. query.setFirstResult(0);//分页
  8. &nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; query.setMaxResults(2);
  9. &nbsp; List<User> lists = query.list();
  10. tx.commit();
  11. HibernateSessionFactory.closeSession();
  12. return lists;
  13. }
  14. public static void main(String[] args) {
  15. UserDaoImpl user = new UserDaoImpl();
  16. System.out.println(user.findAll().size());
  17. }
  18. }

访问的时候其工作流程:

1.读取并解析配置文件;

2.Configuration负责读取并创建映射信息,创建sessionfactory;

3.SessionFactory负责创建session;

4.Transaction负责开启事物Transaction;

5.Query负责执行持久化操作;

6.Transaction负责提交实物;

7.关闭session;

8.关闭sessionfactory。

持久化对象的三种状态:

Hibernate核心接口

Hibernate有五大核心接口,分别是:Session Transaction Query SessionFactoryConfiguration 。这五个接口构成了Hibernate运行的基本要素,可以执行存取,持久化,事务管理等操作。这五个接口可以位于系统的业务逻辑层和持久化层。下面是一张Hibernate的关系图:

Session接口:

Session接口 Session 接口对于Hibernate 开发人员来说是一个最重要的接口。然而在Hibernate中,实例化的Session是一个轻量级的类,创建和销毁它都不会占用很多资源。这在实际项目中确实很重要,因为在客户程序中,可能会不断地创建以及销毁Session对象,如果Session 的开销太大,会给系统带来不良影响。但是Session对象是非线程安全的,因此在你的设计中,最好是一个线程只创建一个Session对象。 session可以看作介于数据连接与事务管理一种中间接口。我们可以将session想象成一个持久对象的缓冲区,Hibernate能检测到这些持久对象的改变,并及时刷新数据库。我们有时也称Session是一个持久层管理器,因为它包含这一些持久层相关的操作, 诸如存储持久对象至数据库,以及从数据库从获得它们。需要注意的是,Hibernate的session不同于JSP 应用中的HttpSession。当我们使用session这个术语时,我们指的Hibernate 中的session,而我们以后会将HttpSesion 对象称为用户session。

SessionFactory接口:

SessionFactroy接口负责初始化Hibernate。它充当数据存储源的代理,并负责创建Session对象。这里用到了工厂模式。需要注意的是SessionFactory并不是轻量级的,因为一般情况下,一个项目通常只需要一个SessionFactory就够,当需要操作多个数据库时,可以为每个数据库指定一个SessionFactory。

Transaction接口

Transaction接口负责事务相关的操作,一般在Hibernate的增删改中出现,但是使用Hibernate的人一般使用Spring去管理事务。

Query接口

Query负责执行各种数据库查询。它可以使用HQL语言或SQL语句两种表达方式。它的返回值一般是List。需要自己转换。

Configuration接口:

Configuration对象用于配置并根启动Hibernate。Hibernate应用通过Configuration实例来指定对象—关系映射文件的位置或者动态配置Hibernate的属性,然后创建SessionFactory实例。我们可以查看Configuration的源代码,它的configure()方法是这样实现的:

  1. public Configuration configure() throwsHibernateException {
  2. configure("/hibernate.cfg.xml" );//此处指定了ORM文件的位置
  3. return this;
  4. }

我们看到它是在这里指定了ORM文件的位置,这就是为什么Hibernate总是默认到classpath下去寻找hibernate.cfg.xml文件的原因了。实际上我们还可以通过configure(String resource)来动态的指定配置文件,只不过通常我们都是采用的默认设置罢了。这样的话我们的配置文件就都被读取了,同时配置文件中通过<mapping>元素引入的映射文件也被读取了。

Hibernate运行过程:

1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件

2.由hibernate.cfg.xml中的<mappingresource="com/xx/User.hbm.xml"/>读取并解析映射信息

3.通过config.buildSessionFactory();//创建SessionFactory

4.sessionFactory.openSession();//打开Sesssion

5.session.beginTransaction();//创建事务Transation

6.persistent operate持久化操作 //一般指Save这个方法

7.session.getTransaction().commit();//提交事务

8.关闭Session

9.关闭SesstionFactory

Hibernate工作流程的更多相关文章

  1. spring+hibernate工作流程文件名理解

    reg.jsp regsuccess.jsp User.java UserDAO.java UserDAOImpl.java User.hbm.xml Reg.java RegImpl.java Re ...

  2. hibernate工作流程、session

    hibernate是对jdbc的封装,不建议直接使用jdbc的connection操作数据库,而是通过session操作数据库.session可以理解为操作数据库的对象. session与connec ...

  3. Hibernate的工作流程以及三种状态

    Hibernate的工作流程: 1. 读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3. 打开Sesssion 4.创建事务Transation 5. 持久化操作 6. ...

  4. Hibernate的工作流程以及三种状态(面试题)

    Hibernate的工作流程以及三种状态 部分转载自:http://www.cnblogs.com/fifiyong/p/6390699.html Hibernate的工作流程: 1. 读取并解析配置 ...

  5. SpringMVC的工作流程?Mybatis和hibernate区别?

    SpringMVC的工作流程?1. 用户发送请求至前端控制器DispatcherServlet2. DispatcherServlet收到请求调用HandlerMapping处理器映射器.3. 处理器 ...

  6. Hibernate工作原理及为什么要用?

    Hibernate工作原理及为什么要用? 原理:1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件2.由hibernate.cfg.x ...

  7. Hibernate工作原理及为什么要用?(转http://www.cnblogs.com/javaNewegg/archive/2011/08/28/2156521.html)

    原理:1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件2.由hibernate.cfg.xml中的<mapping resou ...

  8. SSH三大框架的各自工作流程

    一.Struts2的工作流程:1.用户在客户端发起请求,客户端会初始化一个servlet容器请求:2.servlet容器把请求会传递给context容器,context容器找到目标web工程.3.进行 ...

  9. Mybatis第一篇【介绍、快速入门、工作流程】

    什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...

随机推荐

  1. [LeetCode] Rotate Image [26]

    题目 You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise ...

  2. Unity插件之NGUI学习(1)—— 环境搭建

    Unity官网http://unity3d.com/unity/download下载最新版本号4.5.4 在圣典论坛上找到破解补丁(Windows)版本号tid=18741&fid=8&quo ...

  3. C-Free 您不能使用调试解决方案

    什么时候C-Free 当您调试 找不到gdb.exe解决方案 http://www.programarts.com/ C-Free 官方网站 下载Mingw或者其他编译器 版权声明:本文博主原创文章. ...

  4. 动画原理——脉动(膨胀缩小)&&无规则运动

    书籍名称:HTML5-Animation-with-JavaScript 书籍源码:https://github.com/lamberta/html5-animation 1.脉动是一种半径r来回反复 ...

  5. 跨文档消息传递----postMessage()

    HTML5 规范中,提出了XDM,又称为 跨文档消息传递,其核心是 postMessage()方法,进行跨域和跨文档消息传递,示例如下: <div class="CrossDocume ...

  6. android入门——数据存储

    首先是SharedPreferences 用户偏好 package com.example.wkp.aboutdata; import android.content.Intent; import a ...

  7. jsp文件中的路径问题

    最近在写一个OA系统,在资源的路径问题上面出现了一点问题,使用相对路径的话不利于文件的改动,所以使用了绝对路径来写. 在jsp文件中   <%= String path = request.ge ...

  8. js获取当前url参数的两方式

    方法一:正则分析法function getQueryString(name) {    var reg = new RegExp("(^|&)" + name + &quo ...

  9. Log4Net Config Appender

    整理了下以前项目中使用的Log4Net的Appender. 1:只记录在一个文件下的 <appender name="RollingFileAppenderFileSize" ...

  10. Android SwipeRefreshLayout

    首先介绍一下 SwipeRefreshLayout ,由于下拉刷新使用的人比较多,于是谷歌自己就做了一个下拉刷新的控件. android.support.v4.widget.SwipeRefreshL ...