昨天,一下午都被一个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. jsp servlet 的 请求转发和重定向

    以前对于servlet和servlet/jsp之间的跳转路径问题感到很迷惑,今天亲自动手实验了一把,总结如下: servlet已经是项目根路径下面的资源了,所以servlet跳转的时候,在跳转路径上面 ...

  2. [Caffe]:关于*** Aborted at 1479432790 (unix time) try "date -d @1479432790" 错误的另一种原因

    问题:设置solver.prototxt时,lr_policy:"step",运行时出现下面问题 *** Aborted at (unix time) try "date ...

  3. Luogu5055 【模板】可持久化文艺平衡树(fhq-treap)

    注意下传标记时也需要新建节点.空间开的尽量大. #include<iostream> #include<cstdio> #include<cmath> #inclu ...

  4. bzoj 2599: [IOI2011]Race (点分治 本地过了就是过了.jpg)

    题面:(复制别人的...) Description 给一棵树,每条边有权.求一条路径,权值和等于K,且边的数量最小. Input 第一行 两个整数 n, k第二..n行 每行三个整数 表示一条无向边的 ...

  5. MT【66]寻找对称中心

    设函数$f(x)=2x-cosx,{a_n}$是公差为$\frac{\pi}{8}$的等差数列,$f(a_1)+f(a_2)+f(a_3)+f(a_4)+f(a_5)=5\pi$,则 $[f(a_3) ...

  6. /dev/null与/dev/zero区别

    /dev/null和/dev/zero的区别 /dev/null,外号叫无底洞,你可以向它输出任何数据,它通吃,并且不会撑着! /dev/zero,是一个输入设备,你可你用它来初始化文件.该设备无穷尽 ...

  7. Mysql服务器处理客户端请求流程

    在日常执行mysql语句的过程中,都是客户端进程向服务器进程发送一段文本(MySQL语句),服务器进程处理后再向客户端进程发送一段文本(处理结果). 看似很简单,其实不然,这内容有很多东西是需要注意的 ...

  8. bzoj3545 Peaks

    题意:多次求从点x出发经过边权不超过k的边能走到的点中第k大的权值. 解:离线排序 + 并查集 + 线段树合并. 题面有锅...是第k大的权值不是第k大的山. #include <cstdio& ...

  9. 【POJ1961】最短周期串/最大周期 kmp

    引理:\(s[1,i]\) 具有长度为 \(len\) 的循环节的充要条件是:\(len\ |\ i,s[1,i-len]=s[len+1,i]\). 代码如下 #include <cstdio ...

  10. ref实现输入框聚焦

    关于ref我们是怎么理解的呢? 我们可以通过React.createRef()创建一个 ref节点,并将其打印出来. 代码如下: import React,{Component} from 'reac ...