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.
-
In the Project Explorer, right click and then click New and then click Other.
-
At the New dialog, expand Maven and then select Maven Project. Click Next.
-
At the New Maven Project dialog, select Create a simple project, and click Next.
-
At the New Maven Project dialog, enter the following information:
-
Group ID
com.conygre.training
Artifact ID
BasicHibernate
Name
BasicHibernate
-
Click Finish.
-
Open the pom.xml file in your editor (in Eclipse, then click the Source tab).
-
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.
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>4.3.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.1.4.Final</version> </dependency> </dependencies>
Part 2: Creating the Database Tables
-
MySQL should be installed and running on your machine. The script for creating the relevant tables is shown below.
CREATE DATABASE IF NOT EXISTS conygre;
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');
-
Launch the MySQL Workbench and connect to your local MySQL database.
-
Paste the script into the workbench SQL editor and click the lightning bolt button to run it.
- 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
-
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.
-
Create the class with the name
CompactDisc
in the packagecom.conygre.training.entities
. -
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).
-
id
Integer
title
String
artist
String
price
Double
-
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. -
Add implements
Serializable
to the class since it needs to be for it to be usable by JPA to persist data to the database. -
Use the
@Column
annotation on each of the properties specifying which column in the database it maps to. -
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:
package com.conygre.training.entities;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="compact_discs")
public class CompactDisc implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
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="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="conygrePersistentUnit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<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"/>
</properties>
</persistence-unit>
</persistence>
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
-
In your src/main/java folder, create a new Java class called TestCompactDiscs.
-
Within the main method, write suitable code to retrieve all the compact discs. Specifically, your code will need to:
-
Create an EntityManagerFactory
-
Create an EntityManager
-
Look up the CompactDiscs
-
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;
import com.conygre.training.entities.CompactDisc;
public class TestCompactDiscs {
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("conygrePersistentUnit");
EntityManager em = factory.createEntityManager();
Query query = em.createQuery("from CompactDisc");
List discs = query.getResultList();
for (CompactDisc compactDisc : discs) {
System.out.println(compactDisc.getTitle());
}
em.close();
factory.close();
}
}
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: https://github.com/nicktodd/spring-course/tree/master/Solutions/workspace/BasicHibernate
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