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,并且改名为 ...
随机推荐
- 全国计算机等级考试二级教程-C语言程序设计_第12章_C语言中用户标识符的作用域和存储类
生命周期的概念,也就是生存期,仅仅适用于变量. 代码.常量.定义等等都是与程序共存亡的,他们的生命周期就是程序的生命周期. 静态分配:生命周期是整个程序执行周期,内存会一直存在,在main函数执行之前 ...
- javascript小知识1 this的用法
函数的应用: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...
- Hadoop-Yarn-HA集群搭建(搭建篇)
1.前提条件 我学习过程是一块一块深入的,在把hdfs基本弄懂以及HA成功的情况开始尝试搭建yarn的,建议在搭建前先去看一下转载的原理篇,懂了原理后搭建会很快的,再次强调一下hdfs我默认已经搭建成 ...
- 畅通工程续(dijskra+SPFA)
畅通工程续 Time Limit : 3000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total Submiss ...
- 使用过渡场景在多个场景的切换COCOS2D(4)
CCNode有三个方法,使用CCDirector的replaceScene方法替换场景时,每个节点都会调用这三个方法: onEnter与onExit方法在改变场景过程中的特定时刻被调用,这取决于是否使 ...
- Spring中自己主动装配
自己主动装配 在我们了解过constructor-arg和property装配中.都须要配置对应的属性和值或者引用,假设在比較复杂的项目中.就会使得XML的配置变得复杂,自己主动装配能够使用较少的配置 ...
- _00023 Kafka 奇怪的操作_001它们的定义Encoder达到Class数据传输水平和决心
博文作者:妳那伊抹微笑 博客地址:http://blog.csdn.net/u012185296 博文标题:_00023 Kafka 诡异操作_001自己定义Encoder实现Class级别的数据传送 ...
- Timeout expired 超时时间已到. 达到了最大池大小 错误及Max Pool Size设置
参考数据库链接串: <add key="data" value="server=192.168.1.123; Port=3306; uid=root; pwd=ro ...
- oracle update语句的几点写法
update两表关联的写法包括字查询 1.update t2 set parentid=(select ownerid from t1 where t1.id=t2.id); 2. update tb ...
- 连接远程hbase长时间等待问题
确保本地保存了远程主机名: 保存远程hosts