Getting Started with JPA and Hibernate


This is JPA for beginners! In this blog post, we have provided step by step instructions for how to create a bean mapped to a MySQL database table (script provided) that contains some data about Compact Discs (remember them!). The basic Schema consists of a simple one-to-many relationship between a compact_discs table and a tracks table.

Before you begin

This walkthrough assumes that you have installed MySQL as a database and you know the root password! You also need a Java IDE such as IntelliJ, Eclipse, or Netbeans and the JDK installed. If you are unsure as to how to work with these tools, you might want to look at some basic Java before you try this out.

Part 1: Create a Maven Project

Although these specific instructions relate to Eclipse, you can just as easily use Netbeans or IntelliJ. Essentially in these steps you are creating a Maven project with some dependencies.

  1. In the Project Explorer, right click and then click New and then click Other.

  2. At the New dialog, expand Maven and then select Maven Project. Click Next.

  3. At the New Maven Project dialog, select Create a simple project, and click Next.

  4. At the New Maven Project dialog, enter the following information:

Group ID

Artifact ID




  1. Click Finish.

  2. Open the pom.xml file in your editor (in Eclipse, then click the Source tab).

  3. Add the following dependencies to your project (you can paste them from this blog post if you like). They go directly before the closing </project> tag.



Part 2: Creating the Database Tables 

  1. MySQL should be installed and running on your machine. The script for creating the relevant tables is shown below. 

use conygre;
create table compact_discs (id int primary key auto_increment,title varchar (50),artist varchar(30),tracks int,price double);

CREATE TABLE tracks (id int primary key auto_increment, cd_id int not null, title varchar(50),FOREIGN KEY (cd_id) REFERENCES compact_discs(id));

insert into compact_discs values(9,'Is This It','The Strokes',11,13.99);
insert into compact_discs values(10,'Just Enough Education to Perform','Stereophonics',11,10.99);
insert into compact_discs values(11,'Parachutes','Coldplay',10,11.99);
insert into compact_discs values(12,'White Ladder','David Gray',10,9.99);
insert into compact_discs values(13,'Greatest Hits','Penelope',14,14.99);
insert into compact_discs values(14,'Echo Park','Feeder',12,13.99);
insert into compact_discs values(15,'Mezzanine','Massive Attack',11,12.99);
insert into compact_discs values(16,'Spice World','Spice Girls',11,4.99);

insert into tracks values (1, 16, 'Mama');
insert into tracks values (2, 16, 'Wannabe');
insert into tracks values (3, 16, 'Spice up your life');
  1. Launch the MySQL Workbench and connect to your local MySQL database.

  2. Paste the script into the workbench SQL editor and click the lightning bolt button to run it.

  3.   To confirm the tables have been created successfully, in the left hand Schemas pane, click the Refresh button and then you will see your new database called conygre. If you expand it, you will then see the two tables that we created.

Part 3: Create a Mapped Entity Class

  1. Return to your Java IDE, and in the Project Explorer right click on the src/main/java folder and click New and then click Class.

  2. Create the class with the name CompactDisc in the package

  3. Add the following properties along with the get/set methods
    (NOTE: Do not use Primitive types as they cannot be null and the table values might be null for some of these columns).









  1. Add the annotation to specify that the class is an entity, and then the annotation specifying the table that you are mapping it to. These are @Entity and @Table respectively.

  2. Add implements Serializable to the class since it needs to be for it to be usable by JPA to persist data to the database.

  3. Use the @Column annotation on each of the properties specifying which column in the database it maps to.

  4. Add the @Id annotation to the ID field, and to enable the id column to be auto-generated from the database add the @GeneratedValue(strategy=GenerationType.IDENTITY).

The class should now look like this:


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;

public class CompactDisc implements Serializable {
	private int id;
	@Column(name="title") private String title;
	@Column(name="artist") private String artist;
	@Column(name="price") private Double price;
	@Column(name="tracks") private Integer tracks;

        // plus all the getters and setters

Part 4: Creating the persistence.xml file

The configuration for a JPA application, like the location of the database etc. can go into a file called persistence.xml. This file needs to be placed into the META-INF directory of src/main/resources. A partly completed file has been provided for you. Here is one that will work with the project that we are creating.

<persistence xmlns=""            xmlns:xsi=""            xsi:schemaLocation=""
   <persistence-unit name="conygrePersistentUnit" transaction-type="RESOURCE_LOCAL">    <provider>org.hibernate.ejb.HibernatePersistence</provider>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
         <property name="hibernate.connection.driver.class" value="com.mysql.jdbc.Driver"/> 
         <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/conygre"/>
         <property name="hibernate.connection.username" value="root"/>
         <property name="hibernate.connection.password" value="YOURPASSWORD"/>

If you have done much Java Database type coding before, you will recognise the properties in here, since they are the database URL, driver, password and username. Obviously, substitute your database password for the placeholder in the example!

Part 5: Creating a Test Application

  1. In your src/main/java folder, create a new Java class called TestCompactDiscs.

  2. Within the main method, write suitable code to retrieve all the compact discs. Specifically, your code will need to:

    1. Create an EntityManagerFactory

    2. Create an EntityManager

    3. Look up the CompactDiscs

    4. Close the EntityManager and EntityManagerFactory.

Below is an example of the code you could use:

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class TestCompactDiscs {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		EntityManagerFactory factory = 
		EntityManager em = factory.createEntityManager();
		Query query = em.createQuery("from CompactDisc");
		List discs = query.getResultList();
		for (CompactDisc compactDisc : discs) {

3. Run the application and all being well, you will see a list of album titles!

You can find this particular example in the following location:

The link also includes the code to implement a One to Many relationship as well.

Further Training

The following three training courses go into more detail about this topic:

Java Persistence with JPA –  2 days either remote attend or in person

Building and Deploying JEE Applications  –  4 days either remote attend or in person

Enterprise Spring Development –  3 days either remote attend or in person


Add a Comment

Your email address will not be published. Required fields are marked *