Microservice: Create JPA App Using Jakarta Persistence API in Payara Micro
Before We Begin:
In this tutorial, we will configure this application with the following components in mind:
- The microservice application will be a Mavenized Java application.
- We will use MySQL DB Server as a relational database.
- The JDBC data source will be a transactional data source (
XADataSource
).
JDBC Driver Library Configuration With Maven
You need a JDBC driver to connect your Java application with a relational database. The driver is usually 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.
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, a data source is configured inside the web.xml file. In this example, there is another alternative for creating a data source configuration. The example below demonstrates a basic data source configuration pattern for the payara-resource.xml file inside the src/main/java/webapp/WEB-INF folder:
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.
Injecting JPA EntityManager Into Your Application
Once your data source is configured in your payara-resource.xml
file, we need to register your data source inside the persistence.xml
in your src/main/resources/META-INF/persistence.xml
file. The jta-data-source
is and matches the jndi-name
of the data source as specified in the payara-resource.xml
.
You can inject your jakarta.persistence.EntityManager
in your Java application code by specifying your persistence unit MyAppPU
in your PersistenceContext
annotation:
With that, you can get your Java microservice application to connect and interact with a relational database through the Jakarta Persistence API!
Comments
Post a Comment