Hibernate is an object/relational mapping tool for Java environments. What does it mean the term object/relational mapping? simply a technique of mapping a data representation from an object model to a relational data model with a SQL-based schema.

Hibernate tutorial with Eclipse

For this tutorial we'll use the latest stable release of Hibernate 5 which you can download here: http://www.hibernate.org/downloads 

The tutorial will be built using Eclipse, anyway, since we'll create the Project as simple java project you can easily adapt it on any other IDE. Ok, at fist let's create a new Java project. We'll name it "Hibernate tutorial".

Hibernate 5 tutorial Eclipse jboss

Next step will be configuring the Libraries needed to run the Project. We will be adding:

1. A New User Library containing all the JAR files included in the hibernate-release-5.X.X.Final/lib/required

Creating an User Library

An User Library can be created by selecting the Libraries tab | Add Library | User Library. Click on the User Library button and select New. Enter a name for it and add Hibernate libraries by clicking on Add External JARs:

hibernate tutorial Eclipse jboss

2. A JDBC Driver for connecting to the Database. In our case we will use MySQL JDBC Driver:

hibernate libs tutorial eclipse jboss

Adding Java Classes and configuration files

Done with the Project setup, it's time to add Entities which will represent the relational tables. We'll add a Java class named com.sample.model.Person. As you can see, this Class is a sample JavaBean with properties and getters/setters

package com.sample.model;

public class Person {
    Long id;
    String name;
    String surname;
    String address;

    public Long getId() {
        return id;
    }
    private void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}           

Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Create a file named Person.hbm.xml in the same package/folder of your JavaBean Person.

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

    <class name="com.sample.model.Person" table="PERSON">

        <id name="id" column="ID">
            <generator class="native" />
        </id>

        <property name="name">
            <column name="NAME" length="16" not-null="true" />
        </property>

        <property name="surname">
            <column name="SURNAME" length="16" not-null="true" />
        </property>

        <property name="address">
            <column name="ADDRESS" length="16" not-null="true" />
        </property>

    </class>
</hibernate-mapping>
  • The id element is the declaration of the identifier property, name="id" declares the name of the Java property - The column attribute tells Hibernate which column of the PERSON table we use for this primary key.
  • The nested generator element specifies the identifier generation strategy: in this case we used native, which picks the best strategy depending on the configured database (dialect).
  • The fields are enlist as "property". Notice the column attribute is added on every property even if this can be skipped if java property = database field.

Hibernate configuration file

This file contains the configuration information needed by Hibernate to connect to a RDBMS. For Hibernate's configuration, we can use a simple hibernate.properties file, a slightly more sophisticated hibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file.

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <!-- hibernate dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>


        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatetutorial</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">password</property>
        <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

        <!-- Automatic schema creation (begin) === -->
        <property name="hibernate.hbm2ddl.auto">create</property>


        <!-- Simple memory-only cache -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- ############################################ -->
        <!-- # mapping files with external dependencies # -->
        <!-- ############################################ -->

        <mapping resource="com/sample/model/Person.hbm.xml" />

    </session-factory>
</hibernate-configuration>

As you can see, hibernate.cfg.xml configures the dialect, the JDBC parameters, the connection pool, the cache provider and the single classes mapped.
This example uses MySQL as database. You need to create a database named "hibernatetutorial" and assign to the user "hibernate" all the privileges required.

mysql> create database hibernatetutorial;
Query OK, 1 row affected (0.00 sec)

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

mysql> use hibernatetutorial;
Database changed

mysql> grant all privileges on hibernatetutorial to user;
Query OK, 0 rows affected (0.03 sec)

In this configuration file we have set the property "hibernate.hbm2ddl.auto" to true which means automatic drop/creation of the database schema. Remember to comment this line after the first run. At the bottom we have declared the resource "com/sample/Person.hbm.xml" which is the mapping for Class Person.

The hibernate.cfg.xml file needs to be added to the Java classpath. You can include it into the src folder of your Project which is included by default in the classpath.

Coding a Test class

For completing our Hibernate tutorial we'll create a Java Class “TestPerson” in the package “com.sample”. Add the following source code. It includes methods to create entries in the database, to update and to list them.

package com.sample.test;

import java.util.List;
 
import org.hibernate.Query;
import org.hibernate.Session;

import com.sample.model.Person;
import com.sample.util.SessionFactoryUtil;
 
 
public class TestPerson {
 
    public static void main(String[] args) {
        Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
 
        session.beginTransaction();
 
        createPerson(session);
 
        queryPerson(session);
 
    }
 
    private static void queryPerson(Session session) {
    	
    	
    	
        Query query = session.createQuery("from Person");                 
        List <Person>list = query.list();
        java.util.Iterator<Person> iter = list.iterator();
        while (iter.hasNext()) {
 
            Person person = iter.next();
            System.out.println("Person: \"" + person.getName() +"\", " + person.getSurname() +"\", " +person.getAddress());
 
        }
 
        session.getTransaction().commit();
 
    }
 
    public static void createPerson(Session session) {
        Person person = new Person();
 
        person.setName("Barak");
        person.setSurname("Obama");       
        person.setAddress("White House");       
 
        session.save(person);
    }
}

As you can see the TestPerson starts at first building a SessionFactory: this object is used to open up new Sessions. A Session represents a single-threaded unit of work, the SessionFactory is a thread-safe global object, instantiated once.

A Session is a single unit of work and begins when it is first needed, that is when the first call to getCurrentSession() is made. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the Session from the thread and closes it for you.

In this example we use a SessionFactoryUtil class to instantiate the SessionFactory just once:

package com.sample.util;

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


public class SessionFactoryUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Ok, if you have completed all the steps your project should look like this:

project hibernate eclipse jboss wildfly

Run the main class in order to test it. A new row will be inserted, which is confirmed by logging into mysql client:

mysql> select * from PERSON;
+----+-------+---------+-------------+
| ID | NAME  | SURNAME | ADDRESS     |
+----+-------+---------+-------------+
|  1 | Barak | Obama   | White House |
+----+-------+---------+-------------+
1 row in set (0.00 sec)

Hibernate Troubleshooting:

Here are some common runtime errors and their possible solution:

org.hibernate.HibernateException: No CurrentSessionContext configured

You haven't configured the current_session_context_class property. Add this to your hibernate.cfg.xml:
 <property name="current_session_context_class">thread</property>

org.hibernate.MappingException: Unknown entity: sample.hibernate.Person

It's likely that you have not added (or added with wrong Classname/namespace) the Class Mapping file.

Could not parse mapping document from resource sample/hibernate/Person.hbm.xml
Exception in thread "main" java.lang.ExceptionInInitializerError

Maybe you have forgot to add the DTD information at the top of your Person.hbm.xml

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

You are missing the Simply Logging Facade util. Download it http://www.slf4j.org/dist/slf4j-1.5.2.zip and then add either log4j or JDK14 implementation.

0
0
0
s2smodern