Getting Started with Maven | Using Databases | A Program That Uses JPA
This article explains how to create a program that uses JPA.
Preparing persistence.xml
When using JPA, you need to prepare a file named persistence.xml. This file defines the persistence units used by JPA.
Create a resources folder under the main folder. As mentioned earlier, this is registered as a resource folder. Inside that folder, create a folder named “META-INF”, then prepare a file named “persistence.xml” in it.
The source code for persistence.xml is shown below.
<?xml version="1.0" encoding="UTF-8"?>
<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/persistence_2_1.xsd">
<persistence-unit name="sample-persistance" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.devkuma.MyEntity</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:db" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
</properties>
</persistence-unit>
</persistence>
In persistence.xml, prepare a <persistence-unit> tag inside the <persistence> tag and write the persistence unit information there. In this example, the following information is defined.
- Unit name: sample-persistance
- Provider: org.eclipse.persistence.jpa.PersistenceProvider
- Entity class: com.devkuma.MyEntity
- Properties:
- javax.persistence.jdbc.driver (driver class): org.h2.Driver
- javax.persistence.jdbc.url (database URL): jdbc:h2:mem:db
- javax.persistence.jdbc.user (user name): sa
- eclipselink.ddl-generation (EclipseLink setting): drop-and-create-tables
- eclipselink.ddl-generation.output-mode (EclipseLink setting): database
Except for the last two EclipseLink settings, most of these values are required when using JPA. Among them, make sure to prepare the three essential items: the unit name, provider class, and entity class.
The property values inside the <properties> tag depend on the database you use. The driver, URL, and user name are required for most databases. Settings for databases other than H2 are not covered here, so study them separately as needed.
Creating the Entity Class
Once persistence.xml is ready, the next thing you need is an “entity class”. An entity class is the basis for accessing a database with JPA. In JPA, the contents of database tables must be defined as entity classes, and records are handled as instances of those entity classes.
Earlier, com.devkuma.MyEntity was set as the class in persistence.xml. This is the entity class used by the sample-persistance persistence unit. Let’s create this class.
Create a file named “MyEntity.java” in the src/main/java/com/devkuma/ folder, then write the following source code.
package com.devkuma;
import java.util.Date;
import java.util.Calendar;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class MyEntity {
@Id
@GeneratedValue
private Integer id;
private String name;
private String message;
private Date date = Calendar.getInstance().getTime();
public MyEntity(){
super();
}
public MyEntity(String name, String msg){
super();
this.name = name;
this.message = msg;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String msg) {
this.message = msg;
}
public Date getDate() {
return date;
}
@Override
public String toString() {
return "{\n\tid: " + id + ",\n\tname: " + name + ",\n\tmessage: "
+ message+ ",\n\tdate: " + date + "\n}";
}
}
An entity class is a POJO class annotated with @Entity. Add @Id to the field that becomes the primary key, and use @GeneratedValue to indicate that the value is assigned automatically.
After that, prepare the values to store as private fields with their setter and getter methods. These correspond to the columns included in the table. In this example, the fields id, name, message, and date are prepared.
Using MyEntity
Now the environment for using a database with H2 + JPA is ready. Let’s try using it.
A simple sample is shown below. Edit App.java.
package com.devkuma;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class App {
private static EntityManagerFactory factory
= Persistence.createEntityManagerFactory("sample-persistance");
public static void main( String[] args ){
EntityManager manager = factory.createEntityManager();
try {
manager.getTransaction().begin();
manager.persist(new MyEntity("sungjin", "This is sample message!"));
manager.persist(new MyEntity("wonsuk", "안녕하세요!"));
manager.persist(new MyEntity("byeongho", "이것을 테스트입니다."));
manager.getTransaction().commit();
Query query = manager.createQuery("select i from MyEntity i");
List<MyEntity> list = query.getResultList();
int count = 0;
for (MyEntity p : list) {
System.out.print("No," + ++count + " ");
System.out.println(p);
}
System.out.println(" -- total: " + list.size() + " data.");
} finally {
manager.close();
}
}
}
After changing the source, run the following commands to package and execute the program.
mvn package
mvn exec:java
When executed, the following text is printed to the console.
No, 1 {
id : 1
name : sungjin,
message : This is sample message !,
date : Fri Oct 13 21:28:11 JST 2017
}
No, 2 {
id : 2
name : wonsuk,
message : 안녕하세요!,
date : Fri Oct 13 21:28:11 JST 2017
}
No, 3 {
id : 3
name : byeongho,
message : 이것을 테스트입니다. ,
date : Fri Oct 13 21:28:11 JST 2017
}
- total : 3 data.
Here, three dummy entities are created, stored in the database, retrieved again as MyEntity objects, and printed. This confirms that data can be read and written.
This article is not intended to explain how to use JPA in detail, so the detailed explanation is omitted. Still, this gives you the basic way to create a “program that uses JPA”. Start with databases first, then gradually expand the range of libraries you can use.