lishman levelup
«previous  next»


Getting Started
Associations
HQL



Hibernate Quick Start


Get up and running with Hibernate in five easy steps.
The following example uses an Oracle 10g database.

1. Download

Download and install the latest Hibernate Core and Hibernate Annotations packages.

Make sure that the database driver is on the classpath.

2. Database Table

Create and populate the COUNTRY table.
DROP TABLE country;
DROP SEQUENCE hibernate_sequence;

CREATE SEQUENCE hibernate_sequence START WITH 1000;

CREATE TABLE country (
  ctry_id       NUMBER        NOT NULL,
  ctry_name     VARCHAR2(50)  NOT NULL,
  area          NUMBER        NOT NULL,
  CONSTRAINT country_pk PRIMARY KEY (ctry_id),
  CONSTRAINT country_uk UNIQUE (ctry_name)
);

INSERT INTO country (ctry_id, ctry_name, area)
  VALUES(27, 'Ukraine', 233000);
INSERT INTO country (ctry_id, ctry_name, area)
  VALUES(28, 'pain', 95365);
INSERT INTO country (ctry_id, ctry_name, area)
  VALUES(29, 'Columbia', 440831);
INSERT INTO country (ctry_id, ctry_name, area)
  VALUES(224, 'Yugoslavia', 98766);

COMMIT;
hibernate_sequence is used by the @GeneratedValue annotation to automatically generate the next primary key value.

3. Hibernate Configuration File

Create a Hibernate configuration file named hibernate.cfg.xml in the root of your classpath.
<?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>

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

    <!-- Database connection settings -->
    <property name="connection.provider_class">
        org.hibernate.connection.C3P0ConnectionProvider</property>
    <property name="connection.driver_class">
        oracle.jdbc.driver.OracleDriver
    </property>
    <property name="connection.url">
        jdbc:oracle:thin:@localhost:1521:test01
    </property>
    <property name="connection.username">lish</property>
    <property name="connection.password">secret</property>

    <!-- C3P0 connection pool -->
    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.max_statements">50 </property>
    <property name="hibernate.c3p0.idle_test_period">3000 </property>

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

    <!-- Print all generated SQL to the console -->
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>

    <!-- Mapped entities -->
    <mapping class="levelup.world.gettingstarted.Country"/>

  </session-factory>
</hibernate-configuration>
Be sure to change the connection settings (url, username, password) for your database.

4. HibernateUtil

Create the HibernateUtil helper class.
public class HibernateUtil {

  private static SessionFactory sessionFactory;

  static {
    try {

      sessionFactory =
        new AnnotationConfiguration()
            .configure()
            .buildSessionFactory();

    } catch (Throwable e) {
      System.err.println("Initial SessionFactory creation failed." + e);
      throw new ExceptionInInitializerError(e);
    }
  }

  public static SessionFactory getSessionFactory() {
    return sessionFactory;
  }

  public static void shutdown() {
    getSessionFactory().close();
  }
}

5. Country Class

Create the Country class. If you use a different package name, make sure that the mapping element is changed in the Hibernate configuration file.
package levelup.world.gettingstarted;

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

import levelup.world.HibernateUtil;

import org.hibernate.Session;


@Entity
@Table(name="COUNTRY")
public class Country {

  @Id
  @GeneratedValue
  @Column(name="CTRY_ID")
  private Integer id;

  @Column(name="CTRY_NAME")
  private String name;

  private int area;

  @Transient
  private int rank;

  public Integer getId() {
  return id;
  }

  public void setName(String name) {
  this.name = name;
  }

  public String getName() {
  return name;
  }

  public void setArea(int area) {
  this.area = area;
  }

  public int getArea() {
  return area;
  }

  public void setRank(int rank) {
  this.rank = rank;
  }

  public int getRank() {
  return rank;
  }

  public static void main(String[] args) {

  // Save a persistent entity
  // Create a new country called 'Croatia'
  Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();

  Country croatia = new Country();
  croatia.setName("Croatia");
  croatia.setArea(21831);
  int croatiaId = (Integer) session.save(croatia);

  session.getTransaction().commit();


  // Get a persistent entity using an identifier
  // Read Croatia in a new unit of work
  session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();

  croatia = (Country) session.load(Country.class, croatiaId);
  System.out.println(croatia.getName() + " has been created with an id of " + croatiaId);

  session.getTransaction().commit();


  // Update a persistent entity
  // Modify Spain to correct the name and area
  session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();

  Country spain = (Country) session.load(Country.class, 28);
  System.out.print("Country " + spain.getName() +
       ", area " + spain.getArea());

  spain.setName("Spain");
  spain.setArea(195365);
  System.out.println(" has been updated to " + spain.getName() +
         ", area " + spain.getArea());

  session.getTransaction().commit();


  // Delete a persistent entity
  // Remove Yugoslavia
  session = HibernateUtil.getSessionFactory().getCurrentSession();
  session.beginTransaction();

  Country yugoslavia = (Country) session.load(Country.class, 224);
  System.out.println(yugoslavia.getName() + " is about to be deleted");
  session.delete(yugoslavia);

  session.getTransaction().commit();


  HibernateUtil.shutdown();

  }
}

The application structure should look like this.

Getting Stated Application Structure

Run the Country class.
»