05 - Hibernate Example

5.1 Overview

Let’s create a sample application using Eclipse, so that we can run some sample program using Hibernate.

5.2  Create a Java project in Eclipse

To create a Java project in eclipse, Go to File (Newà Java Project (as shown below ).

Fig - Create new Java Project

Enter the name of Java project and click Finish. In this chapter, we have created a project name as “HibernateExample” (see below figure).

Fig - Create java project

Once done you will see the project created under Project explorer .

Fig - Project Explorer

5.3  Add Hibernate libraries (jar files) in project

Now is the time to add the jar files of Hibernate that we have downloaded Chapter 3.

  • Create a folder “lib” in Java project created in Section 5.2. To do so

Right Click on Project -> New -> Folder and give the name “lib”.

Fig - Give folder name

Once done, you can see “lib” folder created.

Fig - Lib folder created

Copy all the jar files (from the lib/required from downloaded Hibernate) and paste in lib folder.

 

  1. antlr-2.7.7.jar
  2. dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.5.Final.jar
  4. hibernate-core-4.3.7.Final.jar
  5. hibernate-jpa-2.1-api-1.0.0.Final.jar
  6. jandex-1.1.0.Final.jar
  7. javassist-3.18.1-GA.jar
  8. jboss-logging-3.1.3.GA.jar
  9. jboss-logging-annotations-1.2.0.Beta1.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. mysql-connector-java-5.1.18-bin.jar

We need to have these jar files in build path (class path). To do so select all the jar files and

Right Click -> Build Path -> Add to Build Path (see below figure)

 

5.4 Create database schema

Create  schema with the name “tutorial”  using  ‘create schema tutorial;”  sql statement in MySQL Workbench.

5.5 Example1 -   Programmatic Configurations

 Let’s create a sample program to understand Programmatic Configurations we discussed in the previous chapter.

5.5.1 Create Student.java 

public class Student {    
    private int id;    
    private String name;    
    private String emailAddress;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmailAddress() {
        return emailAddress;
    }
    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }
}

5.5.2 Create student.hbm.xml in src directory

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Student" table="student">
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="name" column="name" type="string"/>
        <property name="emailAddress" column="email" type="string"/> 
   </class>
</hibernate-mapping>

Create TestStudent.java to use properties file and add Resource() method

import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestStudent {
    public static void main(String a[])
    {
      Properties prop = new Properties();
      prop.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
      prop.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
      prop.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/tutorial");

      prop.setProperty("hibernate.connection.username", "root");
      prop.setProperty("hibernate.connection.password", "password");
      prop.setProperty("hibernate.hbm2ddl.auto", "create");
      prop.setProperty("hibernate.show_sql", "true");

      Configuration cfg = new Configuration();

      cfg.addResource("student.hbm.xml");
        cfg.setProperties(prop);
      SessionFactory factory = cfg.buildSessionFactory();
      factory.close();
    }
}

5.5.4 Run TestStudent.java

On Running the program , we can see the table is created in database and in console log as well.

Fig - Console Log

5.5.5  Formatted SQL in logs

If you want to see the formatted SQL statements on console then add

    prop.setProperty("hibernate.format_sql", "true");

property in TestStudent.java file and rerun the program . You will see below output

Fig - Console log

5.6 Example 2- Configure logging

Lets override Hibernate logging just to display SQL statements on the console . To do so , add log4j.jar file (download it from https://logging.apache.org/log4j/1.2/download.html) and add it in class path.

Create log4j.properties file in src directory with below content

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
log4j.rootLogger=error,stdout
log4j.logger.org.hibernate.SQL=WARN

Run the TestStudent.java again and this time you will just see the SQL statements on the console.

 

This example shows that we can override Hibernate logging settings with our choice.                 

5.7 Example 3 - hibernate.hbm2ddl.auto property in detail

 “hibernate.hbm2ddl.auto” is the most confusing property so discuss this property in detail with the help of example.

Just to recap - hibernate.hbm2ddl.auto property is used to specify if Hibernate to create , update , drop automatically when the application starts. There are five possible values

a) create- this option creates the tables based on mapping files when the application starts and removes if already exists.

b) create-drop- drop the tables when session factory is closed and create when application starts based on mapping files.

c) update – update the tables if already exist or create if not  based on the mapping files.

d) validate – does not create table validates the table against mapping files. Gives errors if mismatch

e) none - does nothing.

NOTE- This option works on Tables not on SCHEMA

5.7.1 Create hibernate.cfg.xml file 

Create a hibernate.cfg.xml file in the src directory with below content

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
     <property name="hibernate.connection.url">
        jdbc:mysql://localhost:3306/tutorial
     </property>
     <property name="hibernate.connection.username">
        root
     </property>
     <property name="hibernate.connection.password">
       password
     </property>
     <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
     <property name="hibernate.hbm2ddl.auto">create</property>
     <property name="show_sql">true</property>
     <property name="hibernate.connection.driver_class">
        com.mysql.jdbc.Driver
     </property>
    
     <mapping resource="account.hbm.xml" />
     </session-factory>
</hibernate-configuration>

5.7.2  Create account.hbm.xml file in src directory

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Account" table="account">
      <meta attribute="class-description">
         This class contains the user account detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="username" column="username" type="string"/>      
   </class>
</hibernate-mapping>

5.7.3 Create Account.java file in src directory

 public class Account {

     private String username;
    private int id;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    @Override
    public String toString() {
        return "Account [username=" + username + ", id=" + id + "]";
    }
}

5.7.4 Create Test.java file in src directory

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class Test {
     
     public static void main(String args[])
     {
        Configuration cfg = new Configuration().configure();
        SessionFactory factory = cfg.buildSessionFactory();
        factory.close();
     }
}

5.7.5  Run Test.java file 

a) As we have <property name="hibernate.hbm2ddl.auto">create</property> in hibernate.xfg.xml file , account table is created automatically. Refer below console output.

Fig - Console output

 

b)Change the value of create to create-drop and re-run the program

 <property name="hibernate.hbm2ddl.auto">create-drop</property> in hibernate.xfg.xml file , account table is created and destroyed automatically. Refer below console output.

Fig - Console output

c)Change the value to none and re-run the program

 <property name="hibernate.hbm2ddl.auto">none</property> in hibernate.xfg.xml file , account table will not be created. Refer below console output.

Fig - Console Output

d)Change the value to update and re-run the program

 <property name="hibernate.hbm2ddl.auto">update</property> in hibernate.xfg.xml file . , account table will  be created if not exists . Refer below console output.

 

Fig - Console Output

e) Add new property in Account.java and corresponding mapping in account.hbm.xml.

public class Account {
  
    private String username;
    private String password;
    private int id;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    @Override
    public String toString() {
        return "Account [username=" + username + ", id=" + id + "]";
    }
}

Updated account.hbm.xml file

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 

<hibernate-mapping>
   <class name="Account" table="account">
      <meta attribute="class-description">
         This class contains the user account detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="username" column="username" type="string"/>
       <property name="password" column="password" type="string"/>
   </class>
</hibernate-mapping>

Re-run the program with  <property name="hibernate.hbm2ddl.auto">update</property> in hibernate.xfg.xml file .

As  account table is already created , it will be updated without loss of data . New column will be crated automatically.

e)Change the value to validate – this will not create table if not exists and validate the table structure against mapping files . Drop the password column from account table and rerun the program. We will get an error because account table does not have password column where as Account.java and mapping file have. With validate mode, Hibernate found discrepancy and hence raised an error.

  <property name="hibernate.hbm2ddl.auto">validate</property>

 

Like us on Facebook