Microservice: Creating a JPA application using Jakarta Persistence API in Payara Micro
Tags: microservices, java, programming
Published: 2022-02-11 01:51:02

In this blog we are going to discuss how your Java microservice application can  connect to and interacts to relational database through the [Jakarta Persistence API](https://jakarta.ee/specifications/persistence/) (latest version at time of writing is version 3.0). You can configure a data source and a JDBC driver so an application that is running on your Payara Micro server can connect with a relational database.

## Before we begin...
This blog tutorial, we will configure this application with the following in mind:
 - The microservice application will be Mavenized Java application.
 - We will use MySQL DB Server as a relational database.
 - The JDBC datasource will be a transactional datasource (`XADataSource`).

## JDBC Driver library configuration with Maven
In order for your Java application to connect with a relational database, you need a JDBC driver, which is typically provided by the database vendor. Fortunately, most database vendors have released their JDBC drivers to a Maven repository.

If you use Maven to build your application, you can add your JDBC driver by adding code that is similar to the following example to your `pom.xml` file.

```xml
    <dependencyManagement>
    	<dependencies>
    		<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>8.0.19</version>
    		</dependency>
    	</dependencies>
    </dependencyManagement>
    
    <dependencies>
    	<dependency>
    		<groupId>mysql</groupId>
    		<artifactId>mysql-connector-java</artifactId>
    	</dependency>
    </dependencies>
```
With Maven, the JDBC driver file will be copied to the `WEB-INF/lib` folder of your application WAR file during the `package` build phase.

## Configuring a Database Datasource 
In the [Payara Blog](https://blog.payara.fish/setting-up-a-data-source-in-payara-micro) a datasource is configured inside the `web.xml` file. In this example there is another alternative in creating a datasource configuration. The following example shows the basic pattern to configure a data source in your `payara-resource.xml` file inside the `src/main/java/webapp/WEB-INF` folder:

```xml
    <!DOCTYPE resources  PUBLIC  "-//Payara.fish//DTD Payara Server 4 Resource Definitions//EN"  "https://raw.githubusercontent.com/payara/Payara-Community-Documentation/master/docs/modules/ROOT/pages/schemas/payara-resources_1_6.dtd">
    <resources>
        <jdbc-resource pool-name="MyAppDS"
                       jndi-name="java:app/jdbc/MyApp"
                       enable="true"/>
        <jdbc-connection-pool name="MySQLPool"
                              res-type="javax.sql.XADataSource"
                              datasource-classname="com.mysql.cj.jdbc.MysqlXADataSource">
            <property name="url" value="jdbc:h2:mem:hibernateExample"/>
            <property name="User" value="testUser"></property>
            <property name="Password" value="testPassword"></property>
            <property name="DatabaseName" value="myapp_db"></property>
            <property name="ServerName" value="localhost"></property>
            <property name="PortNumber" value="3306"></property>
        </jdbc-connection-pool>
    </resources>
```

## Application configuration for relational database connections
To use a data source that is configured in your `payara-resource.xml` file, you can either inject the data source or specify a lookup in your application code. The following examples assume that a `jndi-name` value of `java:app/jdbc/MyApp` is specified as the `jdbc-resource` element attribute in the `payara-resource.xml` file.

```java
    @Resource(name= "java:app/jdbc/MyApp") 
    DataSource mySQLDatasource;
```
## Injecting JPA EntityManager to your application
Once your datasource is configured in your `payara-resource.xml` file, we need to register your datasource inside the `persistence.xml` in your `src/main/resources/META-INF/persistence.xml` file. The `jta-data-source` is & matches the `jndi-name` of the datasource as specified in the `payara-resource.xml`.

```xml
    <?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="MyAppPU" transaction-type="JTA">
    		<jta-data-source>java:app/jdbc/MyApp</jta-data-source>
    		<shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
    		<properties>
    			<!-- JBoss Wildfly's Hibernate 4 specific JPA properties -->
    			<property name="hibernate.cache.use_second_level_cache" value="true" />
    			<property name="hibernate.hbm2ddl.auto" value="validate" /><!-- NEVER: update -->
            	<property name="hibernate.show_sql" value="false" />
            	<property name="hibernate.format_sql" value="false"/>
    			<property name="hibernate.use_sql_comments" value="false" />
    			<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
    			<!--  For Performance monitoring on Hibernate -->
    			<property name="hibernate.generate_statistics" value="false"/>
    			<property name="hibernate.cache.use_structured_entries" value="false"/>
    			
    			<!-- TomEE PluME 1.7.2 and higher with EclipseLink  -->
    			<property name="eclipselink.logging.logger" value="JavaLogger" />
    		</properties>
    	</persistence-unit>
    </persistence>
 ```
You can inject your `EntityManager` in your Java application code by specifying your persistence unit `MyAppPU` in your `PersistenceContext` annotation:

```java
    @PersistenceContext(unitName="MyAppPU")
    private EntityManager entityManager;
```

## In conclusion...
Athough Payara Micro doesn't ship with an admin console (due to its lightweight platform) compared to Payara Server, it is still possible and simple enough to create JDBC Datasource in Payara Micro that can be used in your enterprise Java microservice application. In fact, with the power of Jakarta Persistent API you can write modern enterprise ORM that interacts with popular relational databasesor interact directly once to your relational database by injecting a `DataSource`, even vial a JNDI lookup too!