求解决 SessionFactory 为什么创建失败?
我用的是Hibernate4.2.4,创建SessionFactory失败了。。Hibernate必须的8个jar包都加进来了,没问题的。求各位帮忙看看。 新手,挺急的!……
调用测试代码:
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ThreadLocal<Session> threadLocal;
static{
try {
//创建工厂
Configuration cfg = new Configuration().configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
} catch (HibernateException e) {
System.err.println(e.getMessage());
}
threadLocal = new ThreadLocal<Session>();
}
private HibernateUtil(){
}
// 获取Session
public static Session getSession()throws HibernateException{
Session session = threadLocal.get();
if(session==null){
if(sessionFactory==null){
System.out.println("sessionFactory为空!!!");
}
// 问题出在这里,openSession的时候报空指针,所以我在上面判断sessionFactory,
// 结果确实输出了 sessionFactory为空!!! 求解决sessionFactory 为什么创建失败?
session = sessionFactory.openSession();
threadLocal.set(session);
}
return session;
}
// 关闭Session
public static void closeSession()throws HibernateException{
Session session = threadLocal.get();
if(session!=null){
session.close();
}
threadLocal.set(null);
}
}
调用测试代码:
public class Test {
Session session;
Transaction transaction;
@org.junit.Test
public void test(){
News news = new News("今晚武汉有雨","本报讯:预计今晚武汉地区局部有中到大雨,请注意防范",new Date());
System.out.println(news);
session = HibernateUtil.getSession();
transaction = session.beginTransaction();
session.save(news);
transaction.commit();
HibernateUtil.closeSession();
}
}
...全文
相关推荐
Bean的生命周期AutoWire的配置集合注入注入Hibernate的SessionFactory.pptx
Hibernate的SessionFactory是Hibernate的核心组件,负责创建Hibernate的Session实例。
JSP 开发SSH整合异常解决办法
sessionFactory是Hibernate用于创建session的工厂类,是Hibernate框架中非常核心的组件之一。
最新Struts和Hibernate和Spring经典面试题
Hibernate 工作原理包括读取并解析配置文件、读取并解析映射信息,创建 SessionFactory、打开 Session、创建事务 Transaction、持久化操作、提交事务、关闭 Session
NHibernate 中文文档
SessionFactory通过创建Session来提供对数据库的访问。Session是短暂的、单线程的对象,它封装了ADO.NET连接,并处理与数据库的交互,包括事务管理和对象的持久化。
Hibernate配置常见错误
一、SessionFactory的创建失败错误表现:在初始化SessionFactory时,可能出现“org.hibernate.HibernateException: Could not instantiate


