How to obtain sessionFactory in Hibernate 5.2.x
Version: Hibernate 5.2.12 (test)
Cause: the Configuration. buildSessionFactory () method used in Hibernate 4.3 is outdated (Deprecation ).
Reference: Official Website document 3.2.4. Building the SessionFactory
The latest tool class HibernateUtils code:
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 ();
}
}
Compare the Hibernate version 4.3 code:
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 ();
}
}
Note:
1. The latest 5th rows are equivalent to the following sentence:
SessionFactory = new MetadataSources (ssr). getMetadataBuilder (). build (). getSessionFactoryBuilder (). build ();
2. The configuration file hibernate. cfg. xml is in the/src directory by default.