Hibernate ORM example

0

In this article, I will first show you an example of hibernate as the ORM tool.

Object Relational Mapping

JDBC is fine as long as we are dealing directly with a relational database. If our domain model is rich and is object oriented, then mapping object model to database columns becomes tedious.
This is where we use an ORM tool like hibernate to bridge the gap what we call the ‘Object-Relational Impedance Mismatch’.

In this example, we will persist an employee using ORM approach. The entity class is defined by class Employee. For each entity class, you must define an identifier property to uniquely identify an entity. id is our identifier property. name is a not null property and holds employee name.

Employee:

package com.javarticles.hibernate;

public class Employee {
    private long id;
    private String name;
    private String contact;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String toString() {
        return "Employee: " + name;
    }
}

In order for an ORM framework to persist your objects to a database, it must know the mapping metadata for the entity classes.

We will now configure Employee class and map the columns.

employee.hbm.xml:

<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.javarticles.hibernate">
	<class name="Employee" table="EMP">
		<id name="id" type="long" column="ID">
			<generator class="identity" />
		</id>
		<property name="name" type="string">
			<column name="NAME" length="100" not-null="true" />
		</property>
		<property name="contact" type="string">
			<column name="CONTACT" length="100"/>
		</property>
	</class>
</hibernate-mapping>

Hibernate requires a configuration file to configure properties such as the database settings, its dialect, the mapping metadata’s locations etc. By default, Hibernate will read the hibernate.cfg.xml file from the root of the classpath.
When using XML mapping files to define mapping metadata, you have to specify the locations of the XML files. We do that in <mapping> element, we set the resource attribute to our mapping file employee.hbm.xml.

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">mnrpass</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
	<mapping resource="employee.hbm.xml" />
    </session-factory>
</hibernate-configuration>

We will now run an example to create employee. Once saved, we query it to make sure the row exists in database.
In order to make sure we can run the example multiple times, we first delete the employee if already exists. Points to note:

  • The first step in using Hibernate is to create a Configuration object and ask it to load the Hibernate configuration file.
  • By default, hibernate.cfg.xml is the configuration file. If our configuration file is of the same name, then we just need to call configure() method.
  • You build a Hibernate session factory from this Configuration object.
  • The main interface for object persistence is Session and it is obtained using SessionFactory instance.
  • For any operation that involves database update, such as saveOrUpdate() and delete(), you must start a Hibernate transaction on that session.

HibernateExample:

package com.javarticles.hibernate;

import java.io.IOException;
import java.util.List;

import org.hibernate.MappingException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateExample {

    public static void main(String[] args) throws MappingException, IOException {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction tx = session.getTransaction();
        try {
            tx.begin();
            Query query = session.createQuery("from Employee where name='Joe'");
            List empList = query.list();
            System.out.println("Employees found: " + empList.size());
            for(Employee emp: empList) {
                session.delete(emp);
                System.out.println("Deleted " + emp);
            }
            tx.commit();
            
            System.out.println("Create new employee");
            tx = session.getTransaction();
            tx.begin();
            Employee emp = new Employee();
            emp.setName("Joe");
            session.saveOrUpdate(emp);
            tx.commit();
            
            query = session.createQuery("from Employee where name='Joe'");
            System.out.println("List all employees: " + query.list());
        } catch (RuntimeException e) {
            tx.rollback();
            throw e;

        } finally {
            session.close();
        }
    }
}

Output:

Employees found: 1
Deleted Employee: Joe
Create new employee
List all employees: [Employee: Joe]

Using annotations

Hibernate also supports the use of JPA annotations to define mapping metadata. For JPA annotations, you have to specify the fully qualified names of the entity classes in hibernate.cfg.xml.

Employee:

package com.javarticles.hibernate.annotations;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="emp")
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="id")
    private long id;
    
    @Column(name="name", length=100, nullable=false)
    private String name;
    
    @Column(name="contract", length=100)
    private String contact;
    
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String toString() {
        return "Employee: " + name;
    }   
}

hibernate.cfg.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">mnrpass</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hbm2ddl.auto">update</property>
	<mapping class="com.javarticles.hibernate.annotations.Employee" />
    </session-factory>
</hibernate-configuration>

Download the Source Code

In this article, I have shown you an example of hibernate ORM and JPA annotations. You can download the source code here: hibernateOrmExample.zip

Share.

Leave A Reply