Accessing and persisting data in microservices

duration 20 minutes

Learn how to use Java Persistence API to access and persist data to a database for your microservices.

What you’ll learn

You will learn how to use the Java Persistence API (JPA) to map Java objects to relational database tables and perform create, read, update and delete (CRUD) operations on the data in your microservices.

JPA is a Java EE specification for representing relational database table data as Plain Old Java Objects (POJO). JPA simplifies object-relational mapping (ORM) by using annotations to map Java objects to tables in a relational database. In addition to providing an efficient API for performing CRUD operations, JPA also reduces the burden of having to write JDBC and SQL code when performing database operations and takes care of database vendor-specific differences. This capability allows you to focus on the business logic of your application instead of wasting time implementing repetitive CRUD logic.

The application that you will be working with is an event manager, which is composed of a UI and an event microservice for creating, retrieving, updating, and deleting events. In this guide, you will be focused on the event microservice. The event microservice consists of a JPA entity class whose fields will be persisted to a database. The database logic is implemented in a Data Access Object (DAO) to isolate the database operations from the rest of the service. This DAO accesses and persists JPA entities to the database and can be injected and consumed by other components in the microservice. An Embedded Derby database is used as a data store for all the events.

You will use JPA annotations to define an entity class whose fields are persisted to the database. The interaction between your service and the database is mediated by the persistence context that is managed by an entity manager. In a Java EE environment, you can use an application-managed entity manager or a container-managed entity manager. In this guide, you will use a container-managed entity manager that is injected into the DAO so the application server manages the opening and closing of the entity manager for you.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone
cd guide-jpa-intro

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished application. Give it a try before you proceed.

To try out the application, first navigate to the finish directory and then run the following Maven goal to build the application and run it inside Open Liberty:

cd finish
mvn install liberty:start-server

Point your browser to the http://localhost:9090/eventmanager.jsf URL. The event application does not display any events because no events are stored in the database. Go ahead and click Create Event, located in the left navigation bar. After entering an event name, location and time, click Submit to persist your event entity to the database. The event is now stored in the database and is visible in the list of current events.

Notice that if you stop the Open Liberty server and then restart it, the events created are still displayed in the list of current events. Run the following Maven goals to stop and then restart the server:

mvn liberty:stop-server
mvn liberty:start-server

The events created are still displayed in the list of current events. The Update action link located beside each event allows you to make modifications to the persisted entity and the Delete action link allows you to remove entities from the database.

After you are done checking out the application, stop the Open Liberty server:

mvn liberty:stop-server

Defining a JPA entity class

Navigate to the start directory to begin.

To store Java objects in a database, you must define a JPA entity class. A JPA entity is a Java object whose non-transient and non-static fields will be persisted to the database. Any Plain Old Java Object (POJO) class can be designated as a JPA entity. However, the class must be annotated with the @Entity annotation, must not be declared final and must have a public or protected non-argument constructor. JPA maps an entity type to a database table and persisted instances will be represented as rows in the table.

The Event class is a data model that represents events in the event microservice and is annotated with JPA annotations. Create the Event class in the backendServices/src/main/java/io/openliberty/guides/event/models/ file:

package io.openliberty.guides.event.models;

import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.NamedQuery;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GenerationType;

@Table(name = "Event")
@NamedQuery(name = "Event.findAll", query = "SELECT e FROM Event e")
@NamedQuery(name = "Event.findEvent", query = "SELECT e FROM Event e WHERE "
    + " = :name AND e.location = :location AND e.time = :time")
public class Event implements Serializable {
    private static final long serialVersionUID = 1L;

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "eventId")
    private int id;

    @Column(name = "eventLocation")
    private String location;
    @Column(name = "eventTime")
    private String time;
    @Column(name = "eventName")
    private String name;

    public Event() {

    public Event(String name, String location, String time) { = name;
        this.location = location;
        this.time = time;

    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getLocation() {
        return location;

    public void setLocation(String location) {
        this.location = location;

    public String getTime() {
        return time;

    public void setTime(String time) {
        this.time = time;

    public void setName(String name) { = name;

    public String getName() {
        return name;

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        if (obj == null) {
            return false;
        if (getClass() != obj.getClass()) {
            return false;
        Event other = (Event) obj;
        if (location == null) {
            if (other.location != null) {
                return false;
        } else if (!location.equals(other.location)) {
            return false;
        if (time == null) {
            if (other.time != null) {
                return false;
        } else if (!time.equals(other.time)) {
            return false;
        if (name == null) {
            if ( != null) {
                return false;
        } else if (!name.equals( {
            return false;

        return true;

    public String toString() {
        return "Event [name=" + name + ", location=" + location + ", time=" + time
                + "]";

The following table breaks down the new annotations:



Declares the class as an entity


Specifies details of the table such as name


Specifies a predefined database query that is run by an EntityManager instance.


Declares the primary key of the entity


Specifies the strategy used for generating the value of the primary key. The strategy = GenerationType.AUTO code indicates that the generation strategy is automatically selected


Specifies that the field is mapped to a column in the database table. The name attribute is optional and indicates the name of the column in the table

Configuring JPA

The persistence.xml file is a configuration file that defines a persistence unit. The persistence unit specifies configuration information for the entity manager.

Create the backendServices/src/main/resources/META-INF/persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
    xmlns="" xmlns:xsi=""
    <persistence-unit name="jpa-unit" transaction-type="JTA">
            <property name="eclipselink.ddl-generation" value="create-tables"/>
            <property name="eclipselink.ddl-generation.output-mode" value="both" />

The persistence unit is defined by the <persistence-unit /> XML element. The name attribute is required and is used to identify the persistent unit when using the @PersistenceContext annotation to inject the entity manager later in this guide. The transaction-type="JTA" attribute specifies to use Java Transaction API (JTA) transaction management. Since we are using a container-managed entity manager, JTA transactions must be used.

A JTA transaction type requires a JTA data source to be provided. The <jta-data-source /> element specifies the Java Naming and Directory Interface (JNDI) name of the data source that is used. The data source has already been configured for you in the backendServices/src/main/liberty/config/server.xml file. This data source configuration is where the Java Database Connectivity (JDBC) connection is defined along with some database vendor-specific properties.

The eclipselink.ddl-generation properties are used here so that you aren’t required to manually create a database table to run this sample application. To learn more about the ddl-generation properties, see the JPA Extensions Reference for EclipseLink.

Performing CRUD operations using JPA

The CRUD operations are defined in the DAO. To perform these operations by using JPA, create the backendServices/src/main/java/io/openliberty/guides/event/dao/ file:

package io.openliberty.guides.event.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import io.openliberty.guides.event.models.Event;

import javax.enterprise.context.RequestScoped;
import javax.transaction.Transactional;

public class EventDao {

    @PersistenceContext(name = "jpa-unit")
    private EntityManager em;

    public void createEvent(Event event) {

    public Event readEvent(int eventId) {
        return em.find(Event.class, eventId);

    public void updateEvent(Event event) {

    public void deleteEvent(Event event) {

    public List<Event> readAllEvents() {
        return em.createNamedQuery("Event.findAll", Event.class).getResultList();

    public List<Event> findEvent(String name, String location, String time) {
        return em.createNamedQuery("Event.findEvent", Event.class)
            .setParameter("name", name)
            .setParameter("location", location)
            .setParameter("time", time).getResultList();

To use the entity manager at runtime, inject it into our CDI bean through the @PersistenceContext annotation. The entity manager interacts with the persistence context. Every EntityManager instance is associated with a persistence context. The persistence context manages a set of entities and is aware of the different states that an entity can have. The persistence context synchronizes with the database when a transaction commits.

The class has a method for each CRUD operation, so let’s break them down:

  • The createEvent() method persists an instance of the Event entity class to the data store by calling the persist() method on an EntityManager instance. The entity instance becomes managed and changes to it will be tracked by the entity manager.

  • The readEvent() method returns an instance of the Event entity class with the specified primary key by calling the find() method on an EntityManager instance. If the event instance is found, it is returned in a managed state, but, if the event instance is not found, null is returned.

  • The readAllEvents() method demonstrates an alternative way to retrieve event objects from the database. This method returns a list of instances of the Event entity class by using the Event.findAll query specified in the @NamedQuery annotation on the Event class. Similarly, the findEvent() method uses the Event.findEvent named query to find an event with the given name, location and time.

  • The updateEvent() method creates a managed instance of a detached entity instance. The entity manager automatically tracks all managed entity objects in its persistence context for changes and synchronizes them with the database. However, if an entity becomes detached, you must merge that entity into the persistence context by calling the merge() method so that changes to loaded fields of the detached entity are tracked.

  • The deleteEvent() method removes an instance of the Event entity class from the database by calling the remove() method on an EntityManager instance. The state of the entity is changed to removed and is removed from the database upon transaction commit.

The DAO is injected into the finish/backendServices/src/main/java/io/openliberty/guides/event/resources/ class and used to access and persist data. The @Transactional annotation is used in the EventResource class to declaratively control the transaction boundaries on the @RequestScoped CDI bean. This ensures that the methods run within the boundaries of an active global transaction, which is why it is not necessary to explicitly begin, commit or rollback transactions. At the end of the transactional method invocation, the transaction commits and the persistence context flushes any changes to Event entity instances it is managing to the database.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

When the server is running, go to the http://localhost:9090/eventmanager.jsf URL to view the Event Manager application.

Click Create Event in the left navigation bar to create events that are persisted to the database. After you create an event, it is available to view, update, and delete in the Current Events section.

Testing the application

Create the EventEntityTest test class in the backendServices/src/test/java/it/io/openliberty/guides/event/ file:


import static org.junit.Assert.assertEquals;

import java.util.HashMap;
import javax.json.JsonObject;

import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import io.openliberty.guides.event.models.Event;

public class EventEntityTest extends EventTest {

    private static final String JSONFIELD_LOCATION = "location";
    private static final String JSONFIELD_NAME = "name";
    private static final String JSONFIELD_TIME = "time";
    private static final String JSONFIELD_ID = "id";
    private static final String EVENT_TIME = "12:00 PM, January 1 2018";
    private static final String EVENT_LOCATION = "IBM";
    private static final String EVENT_NAME = "JPA Guide";
    private static final String UPDATE_EVENT_TIME = "12:00 PM, February 1 2018";
    private static final String UPDATE_EVENT_LOCATION = "IBM Updated";
    private static final String UPDATE_EVENT_NAME = "JPA Guide Updated";

    private static final int NO_CONTENT_CODE = Status.NO_CONTENT.getStatusCode();
    private static final int NOT_FOUND_CODE = Status.NOT_FOUND.getStatusCode();

    public static void oneTimeSetup() {
        port = System.getProperty("backend.http.port");
        baseUrl = "http://localhost:" + port + "/";

    public void setup() {
        form = new Form();
        client = ClientBuilder.newClient();

        eventForm = new HashMap<String, String>();

        eventForm.put(JSONFIELD_NAME, EVENT_NAME);
        eventForm.put(JSONFIELD_TIME, EVENT_TIME);

    public void testInvalidRead() {
        assertEquals("Reading an event that does not exist should return an empty list",
            true, getIndividualEvent(-1).isEmpty());

    public void testInvalidDelete() {
        int deleteResponse = deleteRequest(-1);
        assertEquals("Trying to delete an event that does not exist should return the "
            + "HTTP response code " + NOT_FOUND_CODE, NOT_FOUND_CODE, deleteResponse);

    public void testInvalidUpdate() {
        int updateResponse = updateRequest(eventForm, -1);
        assertEquals("Trying to update an event that does not exist should return the "
            + "HTTP response code " + NOT_FOUND_CODE, NOT_FOUND_CODE, updateResponse);

    public void testReadIndividualEvent() {
        int postResponse = postRequest(eventForm);
        assertEquals("Creating an event should return the HTTP reponse code " +
            NO_CONTENT_CODE, NO_CONTENT_CODE, postResponse);

        Event e = new Event(EVENT_NAME, EVENT_LOCATION, EVENT_TIME);
        JsonObject event = findEvent(e);
        event = getIndividualEvent(event.getInt("id"));
        assertData(event, EVENT_NAME, EVENT_LOCATION, EVENT_TIME);

        int deleteResponse = deleteRequest(event.getInt("id"));
        assertEquals("Deleting an event should return the HTTP response code " +
            NO_CONTENT_CODE, NO_CONTENT_CODE, deleteResponse);

    public void testCRUD() {
        int eventCount = getRequest().size();
        int postResponse = postRequest(eventForm);
        assertEquals("Creating an event should return the HTTP reponse code " +
            NO_CONTENT_CODE, NO_CONTENT_CODE, postResponse);

        Event e = new Event(EVENT_NAME, EVENT_LOCATION, EVENT_TIME);
        JsonObject event = findEvent(e);
        assertData(event, EVENT_NAME, EVENT_LOCATION, EVENT_TIME);

        int updateResponse = updateRequest(eventForm, event.getInt("id"));
        assertEquals("Updating an event should return the HTTP response code " +
            NO_CONTENT_CODE, NO_CONTENT_CODE, updateResponse);

        event = findEvent(e);

        int deleteResponse = deleteRequest(event.getInt("id"));
        assertEquals("Deleting an event should return the HTTP response code " +
            NO_CONTENT_CODE, NO_CONTENT_CODE, deleteResponse);
        assertEquals("Total number of events stored should be the same after testing "
            + "CRUD operations.", eventCount, getRequest().size());

    public void teardown() {


The testInvalidRead(), testInvalidUpdate() and testInvalidDelete() methods use a primary key that is not in the database to test reading, updating and deleting an event that does not exist, respectively.

The testIndividualRead() method persists a test event to the database and retrieves the event object from the database using the primary key of the entity.

The testCRUD() method creates a test event and persists it to the database. The event object is then retrieved from the database to verify that the test event was actually persisted. Next, the name, location, and time of the test event are updated. The event object is retrieved from the database to verify that the updated event is stored. Finally, the updated test event is deleted and one final check is done to ensure that the updated test event is no longer stored in the database.

Running the tests

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

 T E S T S
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.703 sec - in

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0

Great work! You’re done!

You learned how to map Java objects to database tables by defining a JPA entity class whose instances are represented as rows in the table. You have injected a container-managed entity manager into a DAO and learned how to perform CRUD operations in your microservice.

Contribute to this guide

Is something missing or broken? Raise an issue, or send us a pull request.