Hibernate quick start example

[Updated: May 29, 2017, Created: May 29, 2017]

This is a quick start Hibernate example. As an ORM framework, Hibernate maps Java classes to database tables. In this example, we are going to use H2 in memory database and hibernate annotation based mapping.

Dependencies

pom.xml

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>5.2.10.Final</version>
</dependency>
<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.193</version>
</dependency>

Hibernate configuration

src/main/resources/hibernate.cfg.xml

<?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="connection.driver_class">org.h2.Driver</property>
        <property name="connection.url">jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</property>
        <property name="dialect">org.hibernate.dialect.H2Dialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.logicbig.example.Person"/>
    </session-factory>
</hibernate-configuration>

Example entity class

package com.logicbig.example;

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

@Entity
public class Person {
  @Id
  @GeneratedValue
  private int id;
  @Column(name = "FULL_NAME")
  private String name;
  private int age;
    .............
}

The main class

package com.logicbig.example;

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

import java.util.List;

public class ExampleMain {
  public static void main(String[] args) {
      SessionFactory sessionFactory = new Configuration().configure()
                                                         .buildSessionFactory();
      try {
          persist(sessionFactory);
          load(sessionFactory);
      } finally {
          sessionFactory.close();
      }
  }

  private static void load(SessionFactory sessionFactory) {
      System.out.println("-- loading persons --");
      Session session = sessionFactory.openSession();
      @SuppressWarnings("unchecked")
      List<Person> persons = session.createQuery("FROM Person").list();
      persons.forEach((x) -> System.out.printf("- %s%n", x));
      session.close();
  }

  private static void persist(SessionFactory sessionFactory) {
      Person p1 = new Person("John", 35);
      Person p2 = new Person("Tina", 30);
      System.out.println("-- persisting persons --");
      System.out.printf("- %s%n- %s%n", p1, p2);

      Session session = sessionFactory.openSession();
      session.beginTransaction();
      session.save(p1);
      session.save(p2);
      session.getTransaction().commit();
  }
}

Output

Hibernate: drop table Person if exists
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table Person (id integer not null, age integer not null, FULL_NAME varchar(255), primary key (id))
-- persisting persons --
- Person{id=0, name='John', age=35}
- Person{id=0, name='Tina', age=30}
Hibernate: call next value for hibernate_sequence
Hibernate: call next value for hibernate_sequence
Hibernate: insert into Person (age, FULL_NAME, id) values (?, ?, ?)
Hibernate: insert into Person (age, FULL_NAME, id) values (?, ?, ?)
-- loading persons --
Hibernate: select person0_.id as id1_0_, person0_.age as age2_0_, person0_.FULL_NAME as FULL_NAM3_0_ from Person person0_
- Person{id=1, name='John', age=35}
- Person{id=2, name='Tina', age=30}

Example Project

Dependencies and Technologies Used :

  • hibernate-core 5.2.10.Final: The core O/RM functionality as provided by Hibernate.
  • h2 1.4.193: H2 Database Engine.
  • JDK 1.8
  • Maven 3.3.9

Hibernate Quick Start Example Select All Download
  • hibernate-getting-started-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • resources

See Also