Java EE之Hibernate的HibernateSessionFactory
昨天,一下午都被一个bug缠身,最后逐层排查,发现是MyEclipse 2014自动生成的HibernateSessionFactory有问题。
后观察网友提供的自动生成的HibernateSessionFactory也不尽一样,难道,这就有些奇怪了,由于课程项目时间紧张,这学期时间过得太紧巴,此bug的原因暂不讨论,以下先贴上正确的HibernateSessionFactory的设计,再贴上错误的HibernateSessionFactory(且很奇怪的是,我做Hibernate的映射demo的时候都是用这个错误的HibernateSessionFactory,都没有出现此问题)。
引用文献: http://www.cnblogs.com/dyllove98/archive/2013/08/07/3243769.html
一、依赖环境
hibernate 5.1.3 Final
二、正确的HibernateSessionFactory
package com.cpms.util; 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.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION; static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} 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 closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null); if (session != null) {
session.close();
}
} /**
* return session factory
*
*/
public static org.hibernate.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;
} }
三、出错的HibernateSessionFactory
package com.cpms.util; import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
//import org.hibernate.service.ServiceRegistryBuilder; /**
* 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.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory; private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry; static {
try {
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
} /**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
} return session;
} /**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(); serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} /**
* 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();
}
} /**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
} }
Java EE之Hibernate的HibernateSessionFactory的更多相关文章
- Java EE之Hibernate异常总结org.hibernate.MappingException: Repeated column in mapping for entity:
解决方案/原因: 一个pojo(JavaBean)中不能有两个属性同时映射到一个数据库字段上 即使是一个属性的两个getter方法也不行 %%%% Error Creating SessionFact ...
- Java EE 之 Hibernate异常总结【4】org.hibernate.exception.SQLGrammarException: could not execute statement
本质原因:配置的Java Bean,由Hibernate自动产生的SQL语句中有语法错误 原因如下: 情况1.存在字段名/表名与数据库关键字冲突 情况2.MySQL5.0以后与MySQL5.0以前事务 ...
- Java EE 之 Hibernate异常解决:org.hibernate.exception.SQLGrammarException: could not execute statement
本质原因:配置的Java Bean,由Hibernate自动产生的SQL语句中有语法错误 原因如下: 情况1.存在字段名/表名与数据库关键字冲突 情况2.MySQL5.0以后与MySQL5.0以前事务 ...
- Java EE之Hibernate异常总结【5】java.lang.StackOverflowError[栈溢出]
Exception in thread "main" java.lang.StackOverflowError at java.lang.reflect.InvocationTar ...
- Java EE之Hibernate异常总结【3】Disabling contextual LOB creation as createClob() method threw error java.lang.reflect.InvocationTargetException
参考文献:https://stackoverflow.com/questions/4588755/disabling-contextual-lob-creation-as-createclob-met ...
- Java EE 之Hibernate异常总结【1】org.hibernate.LazyInitializationException: could not initialize proxy - no Session
字面意义就是不能被初始化. 简单理解就是因为,你使用了lazy=true,这样hibernate在从数据库中调数据的时候是不会把关联的对象查出来的,而是保存一个获取值得方法,在你使用getXXX()调 ...
- Java EE之 Hibernate 5.x版本中SchemaExport的用法
//hibernate 5.0.1 Final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().confi ...
- Java EE之Hibernate异常总结【2】Field 'id' doesn't have a default value
Field 'id' doesn't have a default value问题解决方法 因为assigned是指主键是由人工分配的,而native则指主键值由库自动给出. <generato ...
- 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)
轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...
随机推荐
- map()实现zip()功能
c = (map(lambda x,y:(x,y),[1,2,3],["abd","def","ghi"]))print(list(c)) ...
- 【Linux】自动执行Mysql常用命令脚本
wamp环境下,我可以手敲一遍,但是lamp环境下我绝对不会手敲一遍 好吧~写脚本的确也是一遍~~~~(>_<)~~~~ 函数和后面的触发器中文档上局部是有错误的,所以大家不要一味的相信文 ...
- linq 分组取各组最大值
static List<User> list1 = new List<User>() { new User(){id=1,name="张三"}, new U ...
- Migrate Maven Projects to Java 11
Migrate Maven Projects to Java 11 So you want to migrate to Java 11 but your Maven project is still ...
- MT【18】幂平均不等式的证明
评:证明时对求导要求较高,利用这个观点,对平时熟悉的调和平均,几何平均,算术平均,平方平均有了更深 刻的认识.
- install nagios pnp4nagios on centos 6
安装配置Apache.PHP(忽略此次安装步骤) 安装nagiosrpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release ...
- springmvc源码解析MvcNamespaceHandler之<mvc:view-resolvers>
说在前面 本次主要介绍springmvc配置解析. springmvc配置解析 本次介绍MvcNamespaceHandler. 进入到这个方法org.springframework.web.serv ...
- emwin 之消息 WM_INIT_DIALOG
@2018-08-09 小记 消息 WM_INIT_DIALOG 在创建窗口时首先发送且只在创建窗口时发送即只发送这一次
- hdu5791(DP)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5791 参考博客:https://blog.csdn.net/wuxuanyi27/article/de ...
- P3747 相逢是问候 欧拉定理+线段树
巨难!!! 去年六省联考唯一的一道黑牌题,我今天一天从早到晚,把它从暴力15分怼到了90分,极端接近正解了. bzoj上A了,但是洛谷和loj上面就不行.伪正解会T,奇奇怪怪的类正解会WA.. 那么, ...