由于之前用的是hibernate3,在换成hibernate4.3.11的时候遇到了不少问题:
配置log4j日志
按照hibernate3那样导入所需jar包,可是抛出异常了:
java.lang.NoSuchFieldError:TRACE
上网查了一下,是因为log4j的版本不匹配的原因,我使用的log4j是1.2.9,换成1.2.17就行了
http://coders-kitchen.com/2013/01/18/hibernate-and-java-lang-nosuchfielderror-trace/
所需jar包:
创建SessionFactory出错
换版本的时候第一个想到的就是查文档,替换HibernateUtil类,官方文档提供的HibernateUtil是这样的:
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
return 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;
}
}
可是创建SessionFactory对象时还是抛出异常了
Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
一开始还以为是配置文件写错了,没有设置数据库方言,可以经过检查和上网查资料,Hibernate4的数据库方言设置方法和hibernate3一样,最后在一个帖子中找到解决方法:http://bbs.csdn.net/topics/390746425
但是官方文档提供的HibernateUtil是有错误的,需要改成这样:
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
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
Configuration cfg = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
return cfg.buildSessionFactory(serviceRegistry);
}
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;
}
public static void close() {
HibernateUtil.sessionFactory.close();
}
}
Hibernate各版本创建SessionFactory:
转:http://blog.csdn.net/for_shell/article/details/52829828
暂时就这两个问题,后续应该会有更多…