In this tutorial, as the tutorial introducing basic about Hibernate, not lengthy, I will go straight to an example of JPA with the implementation of Hibernate to give you a first look and understand how JPA works.
First, I will create a Maven project as follows:
Since I’m going to use JPA with Hibernate’s implementation, so I’ll add Hibernate dependencies like this:
1 2 3 4 5 6 7 8 9 10 |
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.2.12.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>5.2.12.Final</version> </dependency> |
I will also use MySQL database so I will also add MySQL Driver dependency as follows:
1 2 3 4 5 |
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> |
Project Lombok:
1 2 3 4 5 6 |
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> |
In this example, we will define a database containing the information of the class and the students of that class as follows:
1 2 3 4 5 |
CREATE TABLE `clazz` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
1 2 3 4 5 6 7 8 9 10 11 |
CREATE TABLE `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `code` varchar(10) NOT NULL, `date_of_birth` datetime DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `clazz_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `student_clazz_idx` (`clazz_id`), CONSTRAINT `student_clazz` FOREIGN KEY (`clazz_id`) REFERENCES `clazz` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
The preparation steps are finished, now we start going to the main part of this tutorial.
First, in order to work with clazz and students tables in the database, we will map the tables and columns of these tables to Java object first (ORM).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.huongdanjava.jpa; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Table @Getter @Setter public class Clazz { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String name; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.huongdanjava.jpa; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Table @Getter @Setter public class Students { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private String name; @Column private String code; @Column(name = "date_of_birth") private Date dateOfBirth; @Column private String email; @Column(name = "clazz_id") private Long clazzId; } |
Next, we will create a configuration file to work with JPA.
This configuration file will contain information about one or more persistence units. A persistence unit is a collection of information about which Java objects map to the tables in the database and information about the connection to the database, username, and password. In addition, it contains some other configuration information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence_2_1.xsd"> <persistence-unit name="jpaexample" transaction-type="RESOURCE_LOCAL"> <class>com.huongdanjava.jpa.Clazz</class> <class>com.huongdanjava.jpa.Students</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpa_example" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="123456" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.use_sql_comments" value="true" /> </properties> </persistence-unit> </persistence> |
I will explain in detail these configurations in some incoming tutorials.
Normally, we will name this configuration file persistence.xml and this file will be located in the /src/main/resources/META-INF directory of the project.
OK, we’re done, so now how to use those configuration information.
We will use the Persistence object of JPA to read that configuration information and use the EntityManagerFactory object to contain them.
1 |
EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaexample"); |
Notice that, jpaexample is the name of the persistence unit that we have declared in the configuration file.
And now, we can use the EntityManagerFactory object to work.
To work with JPA, we will get an EntityManager object from the EntityManagerFactory.
1 |
EntityManager em = emf.createEntityManager(); |
If you need an operation related to updating the database, we need to open a new transaction. If not then do not need to open the transaction. Here, I need to add a new class, so I will open a transaction as follows:
1 2 |
EntityTransaction transaction = em.getTransaction(); transaction.begin(); |
Here we will add a new record to the clazz table so we will initialize the new Clazz object:
1 2 |
Clazz clazz = new Clazz(); clazz.setName("Class A"); |
And use the EntityManager object to save this Clazz object to the database:
1 2 |
em.persist(clazz); transaction.commit(); |
The entire code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.huongdanjava.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; public class Application { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("jpaexample"); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Clazz clazz = new Clazz(); clazz.setName("Class A"); em.persist(clazz); transaction.commit(); } } |
Result: