Hibernate工作流程
Hibernate创建步骤
(五大核心接口:Configuration/SessionFactory/Session/Transaction/Query)
1.新建工程,导入需要的jar包。
2.利用MyEclipse自动生成功能在工程中创建hibernate.cfg.xml配置文件和
HibernateSessionFactory.java工具类。生成的主要内容如下:
hibernate.cfg.xml:
- <hibernate-configuration>
- <session-factory>
- <property name="connection.username">root</property>
- <property name="connection.url">
- jdbc:mysql://localhost:3306/databasename
- </property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="myeclipse.connection.profile">
- dangdang
- </property>
- <property name="connection.password">root</property>
- <property name="connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <mapping resource="entity/User.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
- package com.hibernate;
- import java.sql.SQLException;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.cfg.Configuration;
- /**
- * Configures and provides access to Hibernate sessions, tied to the
- * current thread of execution. Follows the Thread Local Session
- * pattern, see {@link http://hibernate.org/42.html}.
- */
- public class HibernateSessionFactory {
- /**
- * Location of hibernate.cfg.xml file.
- * NOTICE: Location should be on the classpath as Hibernate uses
- * #resourceAsStream style lookup for its configuration file. That
- * is place the config file in a Java package - the default location
- * is the default Java package.<br><br>
- * Defaults: <br>
- * <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml"</code>
- * You can change location with setConfigFile method
- * session will be rebuilded after change of config file
- */
- private static String CONFIG_FILE_LOCATION = "/com/hibernate/hibernate.cfg.xml";
- private static final ThreadLocal threadLocal = new ThreadLocal();
- private static Configuration configuration = new Configuration();
- private static SessionFactory sessionFactory;
- private static String configFile = CONFIG_FILE_LOCATION;
- private HibernateSessionFactory() {
- }
- /**
- * Returns the ThreadLocal Session instance. Lazy initialize
- * the <code>SessionFactory</code> if needed.
- *
- * @return Session
- * @throws HibernateException
- */
- public static Session getCurrentSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- try {
- if (session == null || !session.isOpen()|| session.connection().isClosed()) {
- if (sessionFactory == null) {
- rebuildSessionFactory();
- }
- session = (sessionFactory != null) ? sessionFactory.openSession()
- : null;
- threadLocal.set(session);
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return session;
- }
- /**
- * Rebuild hibernate session factory
- *
- */
- public static void rebuildSessionFactory() {
- try {
- configuration.configure(configFile);
- sessionFactory = configuration.buildSessionFactory();
- } catch (Exception e) {
- System.err
- .println("%%%% Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- /**
- * Close the single hibernate session instance.
- *
- * @throws HibernateException
- */
- public static void closeCurrentSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- threadLocal.set(null);
- if (session != null) {
- session.close();
- }
- }
- /**
- * return session factory
- *
- */
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- /**
- * return session factory
- *
- * session factory will be rebuilded in the next call
- */
- public static void setConfigFile(String configFile) {
- HibernateSessionFactory.configFile = configFile;
- sessionFactory = null;
- }
- /**
- * return hibernate configuration
- *
- */
- public static Configuration getConfiguration() {
- return configuration;
- }
- }
3.创建UserDao接口和接口的实现类UserDaoImpl,实现类中测试:
UserDaoImpl.java:
- public class UserDaoImpl implements UserDao {
- public List<User> findAll() {
- Session session = HibernateSessionFactory.getSession();
- Transaction tx = session.beginTransaction();
- Query query = session.createQuery("from User");
- query.setFirstResult(0);//分页
- query.setMaxResults(2);
- List<User> lists = query.list();
- tx.commit();
- HibernateSessionFactory.closeSession();
- return lists;
- }
- public static void main(String[] args) {
- UserDaoImpl user = new UserDaoImpl();
- System.out.println(user.findAll().size());
- }
- }
访问的时候其工作流程:
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()方法是这样实现的:
- public Configuration configure() throwsHibernateException {
- configure("/hibernate.cfg.xml" );//此处指定了ORM文件的位置
- return this;
- }
我们看到它是在这里指定了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工作流程的更多相关文章
- spring+hibernate工作流程文件名理解
reg.jsp regsuccess.jsp User.java UserDAO.java UserDAOImpl.java User.hbm.xml Reg.java RegImpl.java Re ...
- hibernate工作流程、session
hibernate是对jdbc的封装,不建议直接使用jdbc的connection操作数据库,而是通过session操作数据库.session可以理解为操作数据库的对象. session与connec ...
- Hibernate的工作流程以及三种状态
Hibernate的工作流程: 1. 读取并解析配置文件 2.读取并解析映射信息,创建SessionFactory 3. 打开Sesssion 4.创建事务Transation 5. 持久化操作 6. ...
- Hibernate的工作流程以及三种状态(面试题)
Hibernate的工作流程以及三种状态 部分转载自:http://www.cnblogs.com/fifiyong/p/6390699.html Hibernate的工作流程: 1. 读取并解析配置 ...
- SpringMVC的工作流程?Mybatis和hibernate区别?
SpringMVC的工作流程?1. 用户发送请求至前端控制器DispatcherServlet2. DispatcherServlet收到请求调用HandlerMapping处理器映射器.3. 处理器 ...
- Hibernate工作原理及为什么要用?
Hibernate工作原理及为什么要用? 原理:1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件2.由hibernate.cfg.x ...
- Hibernate工作原理及为什么要用?(转http://www.cnblogs.com/javaNewegg/archive/2011/08/28/2156521.html)
原理:1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件2.由hibernate.cfg.xml中的<mapping resou ...
- SSH三大框架的各自工作流程
一.Struts2的工作流程:1.用户在客户端发起请求,客户端会初始化一个servlet容器请求:2.servlet容器把请求会传递给context容器,context容器找到目标web工程.3.进行 ...
- Mybatis第一篇【介绍、快速入门、工作流程】
什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...
随机推荐
- [LeetCode] Rotate Image [26]
题目 You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise ...
- Unity插件之NGUI学习(1)—— 环境搭建
Unity官网http://unity3d.com/unity/download下载最新版本号4.5.4 在圣典论坛上找到破解补丁(Windows)版本号tid=18741&fid=8&quo ...
- C-Free 您不能使用调试解决方案
什么时候C-Free 当您调试 找不到gdb.exe解决方案 http://www.programarts.com/ C-Free 官方网站 下载Mingw或者其他编译器 版权声明:本文博主原创文章. ...
- 动画原理——脉动(膨胀缩小)&&无规则运动
书籍名称:HTML5-Animation-with-JavaScript 书籍源码:https://github.com/lamberta/html5-animation 1.脉动是一种半径r来回反复 ...
- 跨文档消息传递----postMessage()
HTML5 规范中,提出了XDM,又称为 跨文档消息传递,其核心是 postMessage()方法,进行跨域和跨文档消息传递,示例如下: <div class="CrossDocume ...
- android入门——数据存储
首先是SharedPreferences 用户偏好 package com.example.wkp.aboutdata; import android.content.Intent; import a ...
- jsp文件中的路径问题
最近在写一个OA系统,在资源的路径问题上面出现了一点问题,使用相对路径的话不利于文件的改动,所以使用了绝对路径来写. 在jsp文件中 <%= String path = request.ge ...
- js获取当前url参数的两方式
方法一:正则分析法function getQueryString(name) { var reg = new RegExp("(^|&)" + name + &quo ...
- Log4Net Config Appender
整理了下以前项目中使用的Log4Net的Appender. 1:只记录在一个文件下的 <appender name="RollingFileAppenderFileSize" ...
- Android SwipeRefreshLayout
首先介绍一下 SwipeRefreshLayout ,由于下拉刷新使用的人比较多,于是谷歌自己就做了一个下拉刷新的控件. android.support.v4.widget.SwipeRefreshL ...