Hibernate 5.2.x 中 sessionFactory 的获取方式


版本:Hibernate 5.2.12(2017-11-1测)

起因:Hibernate 4.3 中通用的Configuration.buildSessionFactory()方法过时(Deprecation)。

参考:官网文档 3.2.4. Building the SessionFactory

最新版工具类 HibernateUtils 代码:

public class HibernateUtils {
 private static SessionFactory sessionFactory;
 private static SessionFactory buildSessionFactory(){
  StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure().build();
  sessionFactory = new MetadataSources(ssr).buildMetadata().buildSessionFactory();
  return sessionFactory;
 }
 public static SessionFactory getSessionFactory(){
  return (sessionFactory==null ? buildSessionFactory() : sessionFactory);
 }
 public static Session openSession(){
  return getSessionFactory().openSession();
 }
}

对比 Hibernate 4.3 版代码:

public class HibernateUtils {
 private static SessionFactory sessionFactory;
 private static SessionFactory buildSessionFactory(){
  sessionFactory = new Configuration().configure().buildSessionFactory();
  return sessionFactory;
 }
 public static SessionFactory getSessionFactory(){
  return (sessionFactory==null ? buildSessionFactory() : sessionFactory);
 }
 public static Session openSession(){
  return getSessionFactory().openSession();
 }
}

注意事项:

1、最新版第 5 行与下句等效:

sessionFactory = new MetadataSources(ssr).getMetadataBuilder().build().getSessionFactoryBuilder().build();

2、配置文件 hibernate.cfg.xml 默认在 /src 目录下。

相关内容

    暂无相关文章