DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Split the Monolith: What, When, How
  • Managing Global Data in Microservice Polyglot Persistence Scenarios
  • Mastering System Design: A Comprehensive Guide to System Scaling for Millions (Part 1)
  • Implementing Real-Time Datadog Monitoring in Deployments

Trending

  • Multi-Scale Feature Learning in CNN and U-Net Architectures
  • Monitoring Spring Boot Applications with Prometheus and Grafana
  • AI-Driven Integration in Large-Scale Agile Environments
  • Self-Hosted Inference Doesn’t Have to Be a Nightmare: How to Use GPUStack
  1. DZone
  2. Data Engineering
  3. Databases
  4. Microservice: Creating JPA Application Using Jakarta Persistence API in Payara Micro

Microservice: Creating JPA Application Using Jakarta Persistence API in Payara Micro

In this blog, we will discuss how your Java microservice application can connect to and interact with a relational database through the Jakarta Persistence API.

By 
BUHAKE SINDI user avatar
BUHAKE SINDI
DZone Core CORE ·
Updated Feb. 16, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, we will discuss how your Java microservice application can connect to and interact with a relational database through the Jakarta Persistence API (the latest version at the 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 Microserver can connect with a relational database.

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.

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, 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:

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 myDB;


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.

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 jakarta.persistence.EntityManager in your Java application code by specifying your persistence unit MyAppPU in your PersistenceContext annotation:

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


With that, you can get your Java microservice application to connect and interact with a relational database through the Jakarta Persistence API!

application API microservice Persistence (computer science) Relational database Java Database Connectivity Data (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Split the Monolith: What, When, How
  • Managing Global Data in Microservice Polyglot Persistence Scenarios
  • Mastering System Design: A Comprehensive Guide to System Scaling for Millions (Part 1)
  • Implementing Real-Time Datadog Monitoring in Deployments

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook