Hibernate + Spring beginner's tutorial

Posted on 07-01-2013 08:12 by graham
This tutorial will show you how to integrate Hibernate persistence with your Spring application.

Prerequisites


Before starting this tutorial you should have:
- a basic Spring project created with Maven
- some kind of database server available locally or remotely; this tutorial uses Postgresql database

Creating model


Persistence is all about storing your model into the database and retrieving it. We will start with creating a sample model class that we want to persist. Let's say our app handles personal data and we have an object Person.
public class Person
{
private Integer id;
private String firstName;
private String lastName;
private Date birthDate;
private Integer height;

public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}
public Date getBirthDate()
{
return birthDate;
}
public void setHeight(Integer height)
{
this.height = height;
}
public Integer getHeight()
{
return height;
}
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return id;
}
}

Looks good. Now let's go to our database and create a table to store the data.

Creating database table


This is not a Postgresql tutorial, so all I will say it that we want to have a database table with columns corresponding to fields of the Person object.
CREATE TABLE persons
(
id serial NOT NULL,
firstname character varying(50) NOT NULL,
lastname character varying(100) NOT NULL,
birthdate timestamp without time zone NOT NULL,
height integer,
CONSTRAINT persons_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);

Add Hibernate dependencies to the POM


This tutorial uses Maven, so Hibernate library JARs will be added as dependencies to the POM file. If your app does not use Maven, you need to configure the libraries in a way specific to your project.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.6.6.Final</version>
</dependency>

Optionally you might need to add dependencies required by Hibernate:
<!-- Hibernate library dependecy start -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<!-- Hibernate library dependecy end -->

Please note that not all versions of Hibernate are compatible with all version of the Spring framework. This tutorial uses Spring 3.0.5.RELEASE and Hibernate 3.6.6.Final.

Mapping model to database


Now it's time to map the model class Person to the database table. We will do this using Java persistence annotations. Let's start with the full code, and then we will discuss each annotation in more detail.
@Entity
@Table(name = "persons")
public class Person
{
private Integer id;
private String firstName;
private String lastName;
private Date birthDate;
private Integer height;

public void setId(Integer id)
{
this.id = id;
}

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_seq")
@SequenceGenerator(sequenceName = "persons_id_seq", name = "pk_seq")
@Column(name = "id", unique = true, nullable = false)
public Integer getId()
{
return id;
}

public void setFirstName(String firstName)
{
this.firstName = firstName;
}

@Column(name = "firstname", unique = false, nullable = false)
public String getFirstName()
{
return firstName;
}

public void setLastName(String lastName)
{
this.lastName = lastName;
}

@Column(name = "lastname", unique = false, nullable = false)
public String getLastName()
{
return lastName;
}

public void setBirthDate(Date birthDate)
{
this.birthDate = birthDate;
}

@Column(name = "birthdate", unique = false, nullable = false, length = 18)
public Date getBirthDate()
{
return birthDate;
}

public void setHeight(Integer height)
{
this.height = height;
}

@Column(name = "height", unique = false, nullable = false)
public Integer getHeight()
{
return height;
}
}

Now, this is what specific annotations do. First we want to tell Hibernate that the class represents a persistent entity (the @Entity annotation does this) and that it should be mapped to the persons table:
@Entity
@Table(name = "persons")
public class Person
{
...
}

The next step is to map the identity column. Potgresql is using sequences to generate IDs for new records. Hibernate can use different stategies to generate IDs, and in this example we will tell it to use the built-in Postgresql sequence strategy.
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "pk_seq")
@SequenceGenerator(sequenceName = "persons_id_seq", name = "pk_seq")
@Column(name = "id", unique = true, nullable = false)
public Integer getId()
{
return id;
}

The name of the sequence, persons_id_seq, has to be the same as the name of the sequence created in Postgresql. By default, Postgresql creates the sequence with the name of the table ("persons") concatenated with the name of the ID field ("id") and the "_seq" suffix.

The @Column annotation is used with the properties' getters to associated the property with a database column and specify additional properties of the mapping. E.g. the first name field is mapped the following way:
@Column (name = "firstname", unique = false, nullable = false)
public String getFirstName()
{
return firstName;
}

Attribute name specifies the name of the column, attribute unique tells whether Hibernate should control uniqueness of this field, and attribute nullable tells (obviously) whether null values are allowed for this property.

Summary


You have now successfully created a Hibernate mapping for your model. A next step would be to create a DAO object that will allow you to perform CRUD operations on your model. This you can find in our tutorial about DAO pattern with Hibernate and Spring.
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems