昨天,一下午都被一个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的更多相关文章

  1. Java EE之Hibernate异常总结org.hibernate.MappingException: Repeated column in mapping for entity:

    解决方案/原因: 一个pojo(JavaBean)中不能有两个属性同时映射到一个数据库字段上 即使是一个属性的两个getter方法也不行 %%%% Error Creating SessionFact ...

  2. Java EE 之 Hibernate异常总结【4】org.hibernate.exception.SQLGrammarException: could not execute statement

    本质原因:配置的Java Bean,由Hibernate自动产生的SQL语句中有语法错误 原因如下: 情况1.存在字段名/表名与数据库关键字冲突 情况2.MySQL5.0以后与MySQL5.0以前事务 ...

  3. Java EE 之 Hibernate异常解决:org.hibernate.exception.SQLGrammarException: could not execute statement

    本质原因:配置的Java Bean,由Hibernate自动产生的SQL语句中有语法错误 原因如下: 情况1.存在字段名/表名与数据库关键字冲突 情况2.MySQL5.0以后与MySQL5.0以前事务 ...

  4. Java EE之Hibernate异常总结【5】java.lang.StackOverflowError[栈溢出]

    Exception in thread "main" java.lang.StackOverflowError at java.lang.reflect.InvocationTar ...

  5. 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 ...

  6. Java EE 之Hibernate异常总结【1】org.hibernate.LazyInitializationException: could not initialize proxy - no Session

    字面意义就是不能被初始化. 简单理解就是因为,你使用了lazy=true,这样hibernate在从数据库中调数据的时候是不会把关联的对象查出来的,而是保存一个获取值得方法,在你使用getXXX()调 ...

  7. Java EE之 Hibernate 5.x版本中SchemaExport的用法

    //hibernate 5.0.1 Final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().confi ...

  8. Java EE之Hibernate异常总结【2】Field 'id' doesn't have a default value

    Field 'id' doesn't have a default value问题解决方法 因为assigned是指主键是由人工分配的,而native则指主键值由库自动给出. <generato ...

  9. 轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)

    轻量级Java EE企业应用实战(第4版):Struts 2+Spring 4+Hibernate整合开发(含CD光盘1张)(国家级奖项获奖作品升级版,四版累计印刷27次发行量超10万册的轻量级Jav ...

随机推荐

  1. Review software requirements specification and create test scenarios (what to test for a certain functionality)

    1 srs2 what to test3 establish guidelines on how this deliverable is to be presented , the template4 ...

  2. maven 父工程 消除重复 对子模块进行管理 主要继承依赖

     子类继承父类的 可以不需要groupid与versionid

  3. BZOJ3697采药人的路径——点分治

    题目描述 采药人的药田是一个树状结构,每条路径上都种植着同种药材.采药人以自己对药材独到的见解,对每种药材进行了分类.大致分为两类,一种是阴性的,一种是阳性的.采药人每天都要进行采药活动.他选择的路径 ...

  4. 博弈论基础知识: 巴什博奕+斐波那契博弈+威佐夫博奕+尼姆博弈(及Staircase)(转)

    (一)巴什博奕(Bash Game):只有一堆n个物品,两个人轮流从这堆物品中取物,规定每次至少取一个,最多取m个.最后取光者得胜.若(m+1) | n,则先手必败,否则先手必胜.显然,如果n=m+1 ...

  5. C代码快速构建框架

    #include "stdio.h" typedef char int8_t; typedef short int16_t; typedef int int32_t; typede ...

  6. 洛谷 P1078 文化之旅 解题报告

    P1078 文化之旅 题目描述 有一位使者要游历各国,他每到一个国家,都能学到一种文化,但他不愿意学习任何一种文化超过一次(即如果他学习了某种文化,则他就不能到达其他有这种文化的国家).不同的国家可能 ...

  7. luogu4269 Snow Boots G (并查集)

    对于某个靴子,如果0代表某个格能走,1代表不能走,那么只要连续的1的个数的最大值>=靴子的步长,那这个靴子就不能用. 那么只要对靴子和格子都按深度排个序,然后从大到小来扫一遍(靴子越来越浅,能走 ...

  8. 框架&样式表

    框架   <frameset rows上下拆分,cols左右拆分><fram src选择文件></frameset>. 样式表:“div style”写在body内 ...

  9. C#反射遍历/查询类中的属性以及值

    遍历一个类/或类对象的属性/值,很有用,看个例子 using System; using System.Collections.Generic; using System.Linq; using Sy ...

  10. SQL SERVER与C#数据类型对照表

    分类 SQL SERVER类型 类型说明 C#类型 精确数字 bigint 从 -2^63 (-9223372036854775808) 到 2^63-1 (9223372036854775807)  ...