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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Migrate, Modernize and Build Java Web Apps on Azure: This live workshop will cover methods to enhance Java application development workflow.

Modern Digital Website Security: Prepare to face any form of malicious web activity and enable your sites to optimally serve your customers.

Kubernetes in the Enterprise: The latest expert insights on scaling, serverless, Kubernetes-powered AI, cluster security, FinOps, and more.

A Guide to Continuous Integration and Deployment: Learn the fundamentals and understand the use of CI/CD in your apps.

Related

  • Split the Monolith: What, When, How
  • Managing Global Data in Microservice Polyglot Persistence Scenarios
  • Implementing Real-Time Datadog Monitoring in Deployments
  • Schema Change Management Tools: A Practical Overview

Trending

  • Architecture Decision Records
  • Integrating ChatGPT With ReactJS: A Comprehensive Guide
  • JBang: How to Script With Java for Data Import From an API
  • Why Use TypeScript for Your Projects?
  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.

BUHAKE SINDI user avatar by
BUHAKE SINDI
DZone Core CORE ·
Updated Feb. 16, 22 · Tutorial
Like (4)
Save
Tweet
Share
4.8K 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
  • Implementing Real-Time Datadog Monitoring in Deployments
  • Schema Change Management Tools: A Practical Overview

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: