在用Hibernate4时会发现:
SessionFactory sessiOnFactory= new AnnotationConfiguration().configure().buildSessionFactory();
SessionFactory sessiOnFactory= new AnnotationConfiguration().configure().buildSessionFactory();buildSessionFactory()废弃,相信很多人会觉得为什么废弃这方法,查了网上的资料,综合如下:
Hibernate给了个ServiceRegistry,然后拿到sessionFactory是通过:
SPAN style="FONT-SIZE: 18px"> @BeforeClass public static void beforeClass() { Configuration cOnfiguration= new Configuration(); //new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); //sessiOnFactory= new AnnotationConfiguration().configure().buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessiOnFactory= configuration.buildSessionFactory(serviceRegistry); @BeforeClass public static void beforeClass() { Configuration cOnfiguration= new Configuration(); //new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); //sessiOnFactory= new AnnotationConfiguration().configure().buildSessionFactory(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessiOnFactory= configuration.buildSessionFactory(serviceRegistry);
像网友说的具有注册表存储库功能,功能更多了,上面的方法废弃,其实是hibernate想你用这个类,因为他们写了个更好的东西出来。原来是这样。其实里面的源码还是:
SPAN style="FONT-SIZE: 18px">package cn.framework.dao.util; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { public static SessionFactory sessiOnfactory= null; static { try { // 通过hibernate.cfg.xml 产生一个SessionFactory 还是和原来的方法一样的。。 sessiOnfactory= new Configuration().configure().buildSessionFactory(); } catch (Throwable ce) { ce.printStackTrace(); } } package cn.framework.dao.util; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; public class HibernateUtil { public static SessionFactory sessiOnfactory= null; static { try { // 通过hibernate.cfg.xml 产生一个SessionFactory 还是和原来的方法一样的。。 sessiOnfactory= new Configuration().configure().buildSessionFactory(); } catch (Throwable ce) { ce.printStackTrace(); }
}还是用到我们上面所谓的废弃的方法。
这里有篇文章详细介绍了ServiceRegistry。有兴趣的可以看看。