Java论坛网»Java技术»有关于HibernateSessionFactory问题
有关于HibernateSessionFactory问题
问?:
大家都知道SessionFactory是重量级封装,创建一个SessionFactory是非常耗资源的。所以,一般而言,我们都会写一个静态的方法来获得SessionFactory,以下代码是myEclipse自动生成的代码。
import org.hibernate.HibernateException;
import org.hibernate.Session;
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/>
* Examples: <br/>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
}
这样就大大方便了我们的操作。比如:
Session session = HibernateSessionFactory.currentSession() ; //获取Session对象
Transaction tx = session.beginTransaction(); //事务开始
//进行一些操作
session.save(obj);
tx.commit(); //关闭事务
可要注意,之前我们获取了一个session对象,现问:
是不是每调用一次HibernateSessionFactory.currentSession() ;
都要对应着HibernateSessionFactory.closeSession();
问题来啦,SessionFactory是非常耗资源的,如果关闭的话,那岂不是性能非常的低下。如果不关闭的话,好像又有点不妥。
如果我只获取而不关闭的话,会怎样?
初学hibernate,望大虾解答。
import org.hibernate.HibernateException;
import org.hibernate.Session;
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/>
* Examples: <br/>
* <code>CONFIG_FILE_LOCATION = "/hibernate.conf.xml".
* CONFIG_FILE_LOCATION = "/com/foo/bar/myhiberstuff.conf.xml".</code>
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
/** Holds a single instance of Session */
private static final ThreadLocal threadLocal = new ThreadLocal();
/** The single instance of hibernate configuration */
private static final Configuration cfg = new Configuration();
/** The single instance of hibernate SessionFactory */
private static org.hibernate.SessionFactory sessionFactory;
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session currentSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
try {
cfg.configure(CONFIG_FILE_LOCATION);
sessionFactory = cfg.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* Default constructor.
*/
private HibernateSessionFactory() {
}
}
这样就大大方便了我们的操作。比如:
Session session = HibernateSessionFactory.currentSession() ; //获取Session对象
Transaction tx = session.beginTransaction(); //事务开始
//进行一些操作
session.save(obj);
tx.commit(); //关闭事务
可要注意,之前我们获取了一个session对象,现问:
是不是每调用一次HibernateSessionFactory.currentSession() ;
都要对应着HibernateSessionFactory.closeSession();
问题来啦,SessionFactory是非常耗资源的,如果关闭的话,那岂不是性能非常的低下。如果不关闭的话,好像又有点不妥。
如果我只获取而不关闭的话,会怎样?
初学hibernate,望大虾解答。
答!: 1:
closeSession();应该不是close HibernateSessionFactory 吧
答!: 2:
你可以写个HibernateUtil,这样子就可以关了
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session=new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s=(Session) session.get();
session.set(null);
if (s !=null)
s.close();
}
}
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static Log log=LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try{
sessionFactory=new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
log.error("Initial SessionFactory creation failed.",ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session=new ThreadLocal();
public static Session currentSession() throws HibernateException {
Session s=(Session)session.get();
//Open a new Session, if this Thread has none yet
if (s==null) {
s=sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession() throws HibernateException {
Session s=(Session) session.get();
session.set(null);
if (s !=null)
s.close();
}
}
相关JAVA教程:
大家帮忙看看这个JSTL的问题,从ArrayList中取得map对象,并迭代出map
读取图片问题
JBOSS打出的错误报告帮忙分析原因,多谢
如何配置LOG4J
struts:No getter method for property Teacher.user of...html.BEAN
有没有人做过协同开发的项目-----关于共享屏幕的问题!小女子在线等待!!
Axis1.5 with wss4j问题
java内存泄露
GUI中实现图片上传到服务器
问一个非常棘手麻烦的问题,带有java控件的页面点击进去经常白屏,页面无响应!
Jtable中如何根据Jtable的值来改变其编辑状态??
谁知道用jFreeChart生成两张图表,并且在同一界面上显示他们?