Friday, January 26, 2018

How to connect MySql 5.x using Hibernate 5

In this post, I'll discuss below points

  • How to create 'SessionFactory' and 'Session'
  • How to choose  'dialect'
Create 'SessionFactory' and 'Session'

Hibernate 5 comes with major changes and they change the way we can building 'SessionFactory'

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

....

StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
SessionFactory sf = metadata.getSessionFactoryBuilder().build();
Session session = sf.openSession()

...
Select 'dialect'.

In hibernate 5, we can below below dialects when connecting to the MySQL


  • org.hibernate.dialect.MySQL5Dialect
  • org.hibernate.dialect.MySQL55Dialect
  • org.hibernate.dialect.MySQL57Dialect

Note: org.hibernate.dialect.MySQLDialect is for MySQL 4.x or earlier.

Enjoy...!!

No comments:

Post a Comment