您的位置:首页 > 其它

org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set .

2014-08-10 17:14 525 查看
转自 http://blog.csdn.net/kqygww/article/details/13095575
在Hibernate4中使用时出现的问题。

根据hibernate 4.3.6 manal 中的文档

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
new Configuration().configure().buildSessionFactory(
new StandardServiceRegistryBuilder().build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
}

}

报org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set .

applySettings(cfg.getProperties())是获取hibernate.cfg.xml的配置信息后设置进ServiceRegistryBuilder中,但是在设置之前的cfg(也就是Configuration)没有获取到hibernate.cfg.xml中的信息,所以在运行的时候或出现属性值未设置的情况。

知道了问题的原因所在,解决就好办了,只要在applySettings(cfg.getProperties())之前获取hibernate.cfg.xml的信息并设置到ServiceRegistryBuilder中即可,这样ServiceRegistryBuilder就可以通过这些信息来构建ServiceRegistry。可以通过Configuration的configure()方法获取的hibernate.cfg.xml中的配置信息。

这是Hibernate4获取SessionFactory的方式,原来的buildSessionFactory()已经不推荐在Hibernate4中使用了。

解决后的代码

Configuration cfg = new Configuration().configure();

ServiceRegistry serviceRegistry= new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();

sessionFactory = cfg.buildSessionFactory(serviceRegistry);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐