Hibernate用来获取配置文件的类是Configuration,若用Annotation的话就是AnnotationConfiguration类。
例:Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");//用configure()方法取得。
//或者config.configure();不用加参数,因为只有需要一个//hibernate.cfg.xml在src路径下。Hibernate会自动匹配
取得配置文件后:需要一个Session对象来操作数据库的存取。Session对象是有SessionFactory的对象来产生的。
在4.0版本之前sessionFactory由取得配置文件的对象config.BuildSessionFactory();产生。
SessionFactory sessionFactory =config.buildSessionFactory();
再由sessionFactory.getCurrentSession();方法产生session。
Session session = sessionFactory.getCurrentSession();
有了session对象之后就可以对数据库进行操作了。但hibernate的所有操作都是建立在事务之上的。所以session操作之前要先打开一个事务:
session.beginTransaction();
同理操作完之后要提交事务:
session.getTransaction().commit();
若出错。可回滚:
session.getTransaction().roolback();(这两句可放在tyr{……}catch{……}语句里面)
另外还要关闭session对象:
session.close();
升级到4.0之后取得session的方法有所改变,hibernate增加了一个注册机ServiceRegistryBuilder 类。要先生成一个注册机对象,然后所有的生成SessionFactory的对象要象注册机注册一下再用。生成方法还是config.buildSessionFactory()方法,不过加了个注册机的参数。config.buildSessionFactory(ServiceRegistry registry);
具体方法如下:
ServiceRegistry resgistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
SessionFactory factory = config.buildSessionFactory(resgistry);
Session session = factory.openSession();
hibernate4下拿到SessionFactory的一段经典代码
当我们去拿hibernate4的sessionFactory时,我们发现原来使的一直很顺手的new Configuration().configure().buildSessionFactory()中的buildSessionFactory方法已经过期了,取而代之的是buildSessionFactory(ServiceRegistry serviceRegistry)方法。查看ServiceRegistry的构造方法,顿时感觉天旋地转,这相当地令人抓狂,不过hibernate可能有其自己的考虑。
经过自己去google,发现了一段经典的取ServiceRegistry的代码,不敢独享,特贴出来与大家共享
privatestaticSessionFactory sessionFactory;
privatestaticServiceRegistry serviceRegistry;
privatestaticSessionFactory configureSessionFactory()throwsHibernateException{
Configuration configuration =newConfiguration();
configuration.configure();
serviceRegistry =newServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
两个Hibernate工具类:
package com.test.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class Hbutil
{
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
// the javadoc recommends use of another method
// buildSessionFactory(ServiceRegistry serviceRegistry)
private static SessionFactory configureSessionFactory() throws HibernateException
{
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory()
{
return configureSessionFactory();
}
}
package com.test.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
/**
* Description:
* <br/>网站: <a href="http://www.crazyit.org">疯狂Java联盟</a>
* <br/>Copyright (C), 2001-2012, Yeeku.H.Lee
* <br/>This program is protected by copyright laws.
* <br/>Program Name:
* <br/>Date:
* @author Yeeku.H.Lee kongyeeku@163.com
* @version 1.0
*/
public class HibernateUtil
{
public static final SessionFactory sessionFactory;
static
{
try
{
//采用默认的hibernate.cfg.xml来启动一个Configuration的实例
//由Configuration的实例来创建一个SessionFactory实例
sessionFactory = Hbutil.getSessionFactory();
}
catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
//ThreadLocal可以隔离多个线程的数据共享,因此不再需要对线程同步
public static final ThreadLocal<Session> session= new ThreadLocal<Session>();
public static Session currentSession() throws HibernateException
{
Session s = session.get();
//如果该线程还没有Session,则创建一个新的Session
if (s == null)
{
s = sessionFactory.openSession();
//将获得的Session变量存储在ThreadLocal变量session里
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException
{
Session s = session.get();
if (s != null)
s.close();
session.set(null);
}
}
A 在3.6.8版本中,可以直接用
SessionFactory sf = new Configuration()
.configure() // 直接用hibernate.cfg.xml来进行配置和创建
.buildSessionFactory();
B 在4.0.0版本中,因Configuration().configure()方法被废除了,
故用以下方式来创建
Configuration config = new Configuration()
.addResource("org/monday/domain/Customer.hbm.xml");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.buildServiceRegistry();
SessionFactory sf = config.buildSessionFactory(serviceRegistry);
在此方法中默认使用hibernate.properties文件来进行配置,而hibernate.properties文件中不能添加映射文件(.hbm.xml),所以只能用.addResource("org/monday/domain/Customer.hbm.xml")来添加映射文件,这里必须是全路径。
使用如下方法时,读取hibernate.cfg.xml时会出错(找不到元素 'hibernate-configuration' 的声明)
Unable to perform unmarshalling at line number 4 and column 26 in RESOURCE hibernate.cfg.xml
可能是这个版本对DTD不识别,或者是方法运用错误。
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.configure() //想通过这个来读取hibernate.cfg.xml来进行配置
.buildServiceRegistry();
SessionFactory sf = new MetadataSources( serviceRegistry )
.buildMetadata()
.buildSessionFactory();
C 在4.0及以上版本中,用hibernate.cfg.xml来创建sessionFactory的方法
private static final SessionFactory sessionFactory = buildSessionFactory();
private static ServiceRegistry serviceRegistry;
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
return configuration.buildSessionFactory(serviceRegistry);
参考: http://blog.csdn.net/niuch1029291561/article/details/8244771
http://www.cnblogs.com/lastren/archive/2012/01/29/2331034.html