Hibernate basics

What is Hibernate?

As explained in chapter Basic idea of Hibernate Chapter 1, Introduction to Hibernate, Hibernate is an object relational mapping solution. It provides all the features you need to create a powerful persistence layer for your application. This chapter explains some basic features and will explain the Hibernate architecture. You should read this first if you do not want face any problems later.

Powerful mapping

The mapping is not limited to one class or to one table but you can also map a wide range of object-oriented concepts. The following classes represent an inheritance hierarchy.

public class Plant {
   private Integer id;
   private String name;
public class Tree extends Plant {
   private boolean hasFruits;
public class Flower extends Plant {
   private String color;

They can be mapped to one table containing all columns and having a discriminator column, which distinguish what type a row is. In the picture below plant_type is the discriminator.


There are other options to map classes and subclasses, e.g. One table per subclass.

Another feature is the mapping of relations 1:n, m:n and 1:1. You can map components. For example you create an Address component which is used in Customer and Supplier.

Powerful query languages

Hibernate provides a powerful object-oriented query language named Hibernate Query Language (HQL).

select i from Invoice i inner join fetch i.order

If you have to create queries dynamically, you can use the Hibernate Criteria Queries. The following query filters the player by name, but only if the name is not null:

Criteria criteria = session.createCriteria(Player.class);
if(name != null)
  criteria.add(Restrictions.eq("name", name));
List players = criteria.list();

If you need native SQL or a stored procedure, you can call it from Hibernate as well.