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>

HibernateSessionFactory.java:

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);//分页
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; query.setMaxResults(2);
&nbsp; 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工作流程的更多相关文章

  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. Android的logcat命令详解

    前言          欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处:          CSDN:http://www.csdn.net        ...

  2. 自己写一个strcmp函数(C++)

    题目说明: 写一个函数,实现两个字符串的比较.即自己写一个strcmp函数,函数原型为int strcmp( char * p1, char * p2); 设p1指向字符串s1,p2指向字符串s2.要 ...

  3. 我的RTOS 之六 -- Touch移植(s5pv210+threadx+ucgui+touch)

    非常久没有关注RTOS了,所以也一直没有更新.近期闲了,把GPIO I2C调通了.简单移植了Touch.在S5PV210上使用. 调试I2C时.废了非常多周折,最后借助示波器才发现一个小小的错误.折腾 ...

  4. MPAndroidChart绘制图形表

    最近一个项目需要用到表格进行统计显示,本来用的是的achartengine,后来发现一个更加强大的开源框架MPAndroidChart. 下面简单介绍下MPAndroidChart,MPAndroid ...

  5. 前端新人学习笔记-------html/css/js基础知识点(三)

    这断时间家里有点事,上班也有点任务,所以几天没看视频没来更新了.今天来更新一下了. 一:默认样式重置 但凡是浏览默认的样式,都不要使用. body,p,h1,h2,h3,h4,h5,h6,dl,dd{ ...

  6. SqlServer2008 数据库同步的两种方式(Sql JOB)

    尊重原著作:本文转载自http://www.cnblogs.com/tyb1222/archive/2011/05/27/2060075.html 数据库同步是一种比较常用的功能.下面介绍的就是数据库 ...

  7. 使用关联对象(AssociatedObject)为UIButton添加Block响应

    在开发中,要给UIButton添加点击事件的话,通常的做法是这样的 UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [ ...

  8. 加密传输SSL协议3_非对称加密

    困死了,这里对非对称加密体系开个头,具体的实验明天写 非对称加密体系 为了解决对称加密中密钥的传输的问题,一些天才的数学家就提出了非对称式的加密体系,也称为公钥加密体系. 加密和解密的密钥是不同的.一 ...

  9. python request使用

    相比httplib.urllib,request真是太美丽了,记录下 下载安装地址:http://docs.python-requests.org/en/latest/user/install/#in ...

  10. 什么是JSON对象

    1.什么是json? JSON全称是JavaScript Object Notation,是一种轻量级的数据交换格式.JSON 与XML具有相同的特性,是一种数据存储格式,但是JSON相比XML 更易 ...