This tutorial will help you to write an annotation based hibernate java program which will save some records into a database and fetch them all using Hibernate API. We will use Maven tool to build the project, Eclipse IDE to code and SQLite database to save / retrieve records. SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine. To learn hibernate, following this tutorial you do not have to install any database or SQLite database separately. However to browse the database you can use 'SQLite Manager - Firefox addon' which provides a very nice GUI for SQLite database.

Tools and Technologies used in this article

  1. Hibernate Core 4.1
  2. Maven
  3. SQLite database
  4. SQLite Manager - Firefox addon
  5. JDK 1.6
  6. Eclipse 3.7

1. Create a Java Project using Maven Tool

In the command prompt execute the following command to generate Maven compatible Java project named as 'HibernateHelloWorld'.

mvn archetype:generate -DgroupId=com.srccodes.example.hibernate -DartifactId=HibernateHelloWorld -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

Generated Maven Java Project structure

Maven Java Project structure

2. Update pom.xml

Add dependency of Hibernate core and SQLite jdbc library. Also update 'maven-compiler-plugin' so that it uses compilation level 1.5 onwards. Otherwise annotation (introduced in JDK 5) will not work.
File : pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.srccodes.example.hibernate</groupId>
    <artifactId>HibernateHelloWorld</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>HibernateHelloWorld</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <!-- hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.4.Final</version>
        </dependency>
 
        <!-- SQLite JDBC library -->
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.7.2</version>
        </dependency>
 
        <!-- junit test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.5</source>
                    <target>1.5</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

3. Convert to Eclipse compatible Java project

Open the directory 'HibernateHelloWorld' in command prompt and run the following maven command.

mvn eclipse:eclipse

Screenshot of command prompt
Maven Java Project

On completion of the above command, Maven Java project will be converted to a Eclipse compatible java project.
Eclipse compatible Java Project structure
Eclipse Java Project

4. Import project in Eclipse

Open Eclipse IDE and select from the menu File --> Import --> General --> Existing Projects into Workspace
Existing Projects into Workspace

Browse to the directory of the newly converted Eclipse compatible Java Project and click 'Finish' button.
Browse project

Screenshot of Eclipse project structure
Eclipse project structure

5. Add Hibernate Configuration file

Right click on 'main' and select from context menu 'New' --> 'Folder'.
new folder

Enter 'resources' in the 'Folder name' field and click the 'Finish' button.
resources folder

Copy the 'hibernate.cfg.xml' file in the 'resources' folder.
File: 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="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
        <property name="connection.driver_class">org.sqlite.JDBC</property>
        <property name="connection.url">jdbc:sqlite:mydb.db</property>
        <property name="connection.username"></property>
        <property name="connection.password"></property>
         
        <property name="hibernate.hbm2ddl.auto">update</property>
         
        <mapping class="com.srccodes.example.hibernate.Contact"/>
    </session-factory>
</hibernate-configuration>

Note:
'mydb.db' is the SQLite database file included with the sourcecode attached in 'Download Source Code' section. You can create db file of your own using 'SQLite Manager - Firefox addon' UI. But copy that file inside 'HibernateHelloWorld' project directory directly.

I have set the property 'hibernate.hbm2ddl.auto' to 'update' so that when you will execute the code it will create the database tables of it's own based on the entity class 'com.srccodes.example.hibernate.Contact') we have written and referenced in this configuration file.


6. Configure Java Build Path

Right click on 'HibernateHelloWorld' project and select from context menu 'Properties' --> 'Java Build Path'.
Add 'resources' folder as shown in the screenshot below
Java Build Path

7. Add SQLiteDialect

Copy from attached source code or download SQLiteDialect and add under package 'org.hibernate.dialect' in your project.

Note: dialect is used to help hibernate framework to create underlying database specific SQL query.

8. Write Entity class

Create a class 'Contact' under the package 'com.srccodes.example.hibernate' and copy the following content.

package com.srccodes.example.hibernate;
 
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
/**
 * The persistent class for the contact database table.
 * 
 */
@Entity
@Table(name = "contact")
public class Contact {
    private Integer id;
    private String name;
    private String email;
 
    public Contact() {
 
    }
 
    public Contact(Integer id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }
 
    @Id
    public Integer getId() {
        return this.id;
    }
 
    public void setId(Integer id) {
        this.id = id;
    }
 
    public String getName() {
        return this.name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
}

As we have set 'hibernate.hbm2ddl.auto' property in 'hibernate.cfg.xml' file, hibernate will generate the schema for the first time and for every change of the schema based on the annotation we write in the 'Contact' class.

Annotation '@Table(name = "contact")' will create a table named as'contact' in the SQLite database. As 'id' field of 'Contact' class is annotated as '@Id' so 'id' will be the primary key for the generated table 'contact'.

9. Interact with database using Hibernate API

Copy the following code to 'App' class of package 'com.srccodes.example.hibernate'.

package com.srccodes.example.hibernate;
 
import java.util.List;
import java.util.Properties;
 
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
 
/**
 * Hello world!
 * 
 */
public class App {
    private static SessionFactory sessionFactory = null;  
    private static ServiceRegistry serviceRegistry = null;  
       
    private static SessionFactory configureSessionFactory() throws HibernateException {  
        Configuration configuration = new Configuration();  
        configuration.configure();  
         
        Properties properties = configuration.getProperties();
         
        serviceRegistry = new ServiceRegistryBuilder().applySettings(properties).buildServiceRegistry();          
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);  
         
        return sessionFactory;  
    }
     
    public static void main(String[] args) {
        // Configure the session factory
        configureSessionFactory();
         
        Session session = null;
        Transaction tx=null;
         
        try {
            session = sessionFactory.openSession();
            tx = session.beginTransaction();
             
            // Creating Contact entity that will be save to the sqlite database
            Contact myContact = new Contact(3, "My Name", "[email protected]");
            Contact yourContact = new Contact(24, "Your Name", "[email protected]");
             
            // Saving to the database
            session.save(myContact);
            session.save(yourContact);
             
            // Committing the change in the database.
            session.flush();
            tx.commit();
             
            // Fetching saved data
            List<Contact> contactList = session.createQuery("from Contact").list();
             
            for (Contact contact : contactList) {
                System.out.println("Id: " + contact.getId() + " | Name:"  + contact.getName() + " | Email:" + contact.getEmail());
            }
             
        } catch (Exception ex) {
            ex.printStackTrace();
             
            // Rolling back the changes to make the data consistent in case of any failure 
            // in between multiple database write operations.
            tx.rollback();
        } finally{
            if(session != null) {
                session.close();
            }
        }
    }
}

10. Final project structure

After doing all the changes the overall project structure will look like this
overall project structure

11. Run Your Code

Right click on 'App.java' and select from context menu 'Run As' --> 'Java Application'.

12. Console Output

Now code will save two records in the database and fetch them to print in the console as well.
Console Output
Screenshot of the table using 'SQLite Manager - Firefox addon' UI
SQLite Manager

Download SrcCodes

All code samples shown in this post are available in the following link HibernateHelloWorld.zip

References