How to obtain sessionFactory in Hibernate 5.2.x

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.