Hibernate创建步骤
(五大核心接口:Configuration/SessionFactory/Session/Transaction/Query)
1.新建工程,导入需要的jar包。
2.利用MyEclipse自动生成功能在工程中创建hibernate.cfg.xml配置文件和
HibernateSessionFactory.java工具类。生成的主要内容如下:
hibernate.cfg.xml:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 query.setMaxResults(2); 9 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()方法是这样实现的:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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