Hibernate 5 annotationconfiguration

In Hibernate 5 we can use the annotations to configure entity classes and get SessionFactory without annotationconfiguration class.

Hibernate 5 annotationconfiguration alternative example

Hibernate is very flexible ORM tool and Hibernate 5 also supports annotations for configuring the beans in the system. You can use various annotations to configure the beans in your applications. Annotations like @Entity, @Table, @Id etc..  are available in Hibernate 5 ORM which is used to configure an Entity.

You can use these annotations in case you are using JPA for persistence. JPA is another best API for creating persistence layer for applications.

But if you are just using Hibernate and manually creating SessionFactory in your program then there is change in Hibernate 5, the annotationconfiguration class is no longer available for creating SessionFactory in the application.

In this tutorial we will talk about how to create SessionFactory and get session in Hibernate 5 with new method.

In Hibernate 5 the annotationconfiguration is removed as it was previously marked deprecated. Now in Hibernate 5 to create the instance of SessionFactory you have to use the StandardServiceRegistryBuilder() class.

First of all you have to add the Model class in your application. For example:

@Table(name = "employee")
public class Employee implements Serializable{

	@GeneratedValue(strategy = GenerationType.IDENTITY) 
	private int id;	

The add this class file in hibernate.cfg file

In Hibernate 5 you should use correct dtd configuration. Following hibernate.cfg file shows how to include Hibernate 5 dtd correctly:


<mapping class="net.roseindia.model.Employee" />


Now to create the SessionFactory and getting session you can use following code:

static {
		try {
		StandardServiceRegistry standardRegistry = 
		new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
		Metadata metaData = 
		new MetadataSources(standardRegistry).getMetadataBuilder().build();
			sessionFactory = metaData.getSessionFactoryBuilder().build();
		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);
			throw new ExceptionInInitializerError(th);

	public static SessionFactory getSessionFactory() {

		return sessionFactory;


This way you can get SessionFactory in your Hibenate 5 application. Check following tutorial for complete example in Hibernate 5:

So, you learned the correct way to configure dtd in Hibernate 5 application. Explore following tutorials of Hibernate 5:




We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Hibernate 5 annotationconfiguration

Posted on: December 10, 2017 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Hibernate 5 annotationconfiguration  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image