Friday, 25 January 2013

Hibernate JPA sample project

Here's a simple example of a project that uses JPA with Hibernate as default implementation.

Let's start with the required dependencies:

We're going to use the embedded Derby database.

We will also need the persistence.xml placed in META-INF directory on our classpath :

We're setting Hibernate as our persistence provider and Derby as JDBC driver.
Entity class Person is also specified as belonging to this persistent unit.

It's defined as:

In order to manage Person we need some kind of DAO.  Let's define an interface PersonDao:

For simplicity it has only methods for adding person and finding all persons.

The sample implementation could look like:

And the most important - integration test that checks if everything is glued together correctly:

The whole project can be found at:

To sum up:
it's quite easy to create JPA with Hibernate project, however every entity class needs it's own DAO (unless we use a generic one).
In the next post I'll take a look at Spring Data Jpa project that solves that impediment.

No comments:

Post a Comment