Home Hibernate Hibernate 5 Example with different configurations

Hibernate 5 Example with different configurations

Tutorial to demonstrate configuring Hibernate properties in different ways using hibernate.cfg.xml, hibernate.properties and Java Configuration with an Hibernate 5 + Mysql + Maven example.

1. Hibernate 5 + Mysql + Maven Example

1.1. Used Technologies :

  1. hibernate-core-5.4.18.Final
  2. Maven 3+
  3. Mysql 8

1.2. Maven Dependencies :

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.18.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.20</version>
        </dependency>
    </dependencies>

1.3. Student Entity :

@Entity(name = "Student")
@Table(name = "STUDENT")
public class Student {

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
	@GenericGenerator(name = "native", strategy = "native")
	@Column(name = "ID")
	private Long studentId;

	@Column(name = "FNAME", nullable = false)
	private String firstName;

	@Column(name = "LNAME", unique = true, length = 25)
	private String lastName;

	@Column(name = "CONTACT_NO", length = 15)
	private String contactNo;

        // Setters, getters and toString() omitted
}

1.4. hibernate.cfg.xml :

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
  
    <property name="connection.url">jdbc:mysql://localhost:3306/jpa_jbd?serverTimezone=UTC&useSSL=false</property>
    <property name="connection.username">root</property>
    <property name="connection.password">password</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
  
    <!-- 'show_sql' set true to check sql statements on console else set to false -->
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <!-- use 'create' to Create tables on application startup else use 'update'-->
    <property name="hbm2ddl.auto">create</property>
  
    <!-- JDBC connection pool -->
    <property name="connection.pool_size">5</property>
    <property name="current_session_context_class">thread</property>
 
     <!-- Domain Model classes to be mapped -->
    <mapping class="com.javabydeveloper.domain.Student" />
 
</session-factory>
</hibernate-configuration>

1.5. HibernateUtil :

HibernateUtil is a wrapper around SessionFactory.

public class HibernateUtil {
  
    private static final SessionFactory sessionFactory = buildSessionFactory();
  
    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
  
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
  
    public static void close() {
        // Close all cached and active connection pools
        getSessionFactory().close();
    }
  
}

1.6. Test the configuration and Mapping :

public class App {

	public static void main(String[] args) {

		Session session = HibernateUtil.getSessionFactory().openSession();
		session.beginTransaction();

		Student student = new Student();
		student.setFirstName("John");
		student.setLastName("Bloch");
		student.setContactNo("+1-408-575-1317");

		session.save(student);
		session.getTransaction().commit();

		Query<Student> q = session.createQuery("From Student", Student.class);

		List<Student> resultList = q.list();
		System.out.println("total sudents:" + resultList.size());
		
		for (Student s : resultList) {
			System.out.println("student : " + s);
		}
	}
}

1.7. Output Results :

This is partial output.

total sudents:1
student : Student [studentId=1, firstName=John, lastName=Bloch, contactNo=+1-408-575-1317]

2. Custom .cfg.xml file name

When you call new Configuration().configure() , Hibernate reads all the settings with default file name hibernate.cfg.xml from the class path, later it uses these settings to build SessionFactory. To provide config file with custom name (for example hibernate-dev.cfg.xml) update your HibernateUtils class buildSessionFactory() method with following code.

 private static SessionFactory buildSessionFactory() {
        try {
           
            return new Configuration().configure("hibernate-dev.cfg.xml").buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

3. hibernate.properties instead cfg.xml file

To provide configuration properties using hibernate.properties instead hibernate.cfg.xml file, update buildSessionFactory() method with following code.

When Configuration instance created using new Configuration() , it reads all the System Properties and config properties from hibernate.proprties file by default. You can get all these properties using Environment.getProperties();

private static SessionFactory buildSessionFactory() {
        try {
       
            return new Configuration()
                        // can also use .addPackage("com.javabydeveloper.domain") to configure all models
            		.addAnnotatedClass(Student.class)
            		.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

4. Custom hibernate properties file name instead hibernate.properties

Let’s say the configuration properties file is hibernate-dev.properties, update buildSessionFactory() method with following code.

private static SessionFactory buildSessionFactory() {
        try {
            Properties properties = new Properties();
            properties.load(HibernateUtilCustomPropsFileName.class.getClassLoader().getResourceAsStream("hebernate-dev.properties"));
            
            return new Configuration()
            		.addProperties(properties)
            		.addPackage("com.javabydeveloper.domain")
            		.buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

5. Using Java Configuration instead of configuration files

We can also provide configuration properties using Java code instead providing via cfg.xml or .properties files, update buildSessionFactory() method with following code.

    private static SessionFactory buildSessionFactory() {
        try {
        	
            Properties properties = new Properties();
            properties.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
            properties.put(Environment.URL, "jdbc:mysql://localhost:3306/jpa_jbd?serverTimezone=UTC&useSSL=false");
            properties.put(Environment.USER, "root");
            properties.put(Environment.PASS, "password");
            properties.put(Environment.FORMAT_SQL, "true");
            properties.put(Environment.DIALECT, "org.hibernate.dialect.MySQL8Dialect");
            properties.put(Environment.SHOW_SQL, "true");
            properties.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
            properties.put(Environment.HBM2DDL_AUTO, "create");
            properties.put(Environment.POOL_SIZE, "5");
           
            return new Configuration()
            		.setProperties(properties)
            		.addAnnotatedClass(Student.class)
            		.buildSessionFactory();
            
        } catch (Throwable ex) {
            System.err.println("build SeesionFactory failed :" + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

6. What will happen if hibernate.properties and hibernate.cfg.xml both present in class path?

If hibernate.properties and hibernate.cfg.xml both present in class path, hibernate.cfg.xml setting will override the hibernate.properties values. hibernate.properties configuration values are global Environment properties.

7. Conclusion

In this Tutorial demonstrated configuring Hibernate properties in different ways using hibernate.cfg.xml, hibernate.properties and Java Configuration with an Hibernate 5 + Mysql + Maven example.

You can checkout source code from our github repository.

8. References

  1. Environment Java Doc
  2. Configuration Java Doc
  3. Hibernate 3.3 doc
  4. Hibernate Dialect
  5. JPA MyQL Maven Example

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Follow him on LinkedIn or Twitter or Facebook

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories