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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example
  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • Non-blocking Database Migrations
  • The Complete Tutorial on the Top 5 Ways to Query your Relational Database in JavaScript - Part 1

Trending

  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • A Complete Guide to Modern AI Developer Tools
  • Optimizing Integration Workflows With Spark Structured Streaming and Cloud Services
  1. DZone
  2. Data Engineering
  3. Databases
  4. Connecting Jakarta EE Applications to MySQL Databases Using JPA and Apache DeltaSpike [Video]

Connecting Jakarta EE Applications to MySQL Databases Using JPA and Apache DeltaSpike [Video]

This article shows how to connect a Java web application developed with Jakarta EE and Vaadin to a MySQL database using the Data module of Apache DeltaSpike.

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Updated Jul. 20, 21 · Presentation
Likes (5)
Comment
Save
Tweet
Share
18.3K Views

Join the DZone community and get the full member experience.

Join For Free

This article shows how to connect a Java web application developed with Jakarta EE and Vaadin to a MySQL database using the Data module of Apache DeltaSpike. You can also watch a video version of this tutorial:

Setting up a MySQL Database

Download and install MySQL Community Server. Start the server and connect to it from the command line using:

Plain Text
 
mysql -u root -p


Change root with the username you want to use to connect to the database. Ideally, you should create a database user for your web application instead of using the root user.

Create a new database and set it as the current session database by running the following commands:

MySQL
 
create database jakartaee;
use jakartaee


Create a new table as follows (the statement is executed once you end a line with a semicolon):

MySQL
 
CREATE TABLE users(
    id INT NOT NULL AUTO_INCREMENT,
    email VARCHAR(255),
    birth_date DATE,
    PRIMARY KEY (id)
);


Insert example rows as follows (feel free to insert as many as you want):

MySQL
 
INSERT INTO users(email, birth_date) VALUES("test1@test.com", "2000-10-15");
INSERT INTO users(email, birth_date) VALUES("test2@test.com", "2001-11-16");
INSERT INTO users(email, birth_date) VALUES("test3@test.com", "2002-12-17");


Confirm that you have data in the table by executing the following query:

MySQL
 
SELECT * FROM users;


You can disconnect from the database and exit the client by running the quit command.

Adding the Dependencies

You'll need a Jakarta EE project. You can see how to create a new one suitable for following this tutorial on YouTube. This article's example uses Java 11, Jakarta EE 8, and Vaadin 20.

Add the following dependency in the <dependencyManagement> section of the pom.xml file:

XML
 
<dependencyManagement>
    <dependencies>
        ...
        <dependency>
            <groupId>org.apache.deltaspike.distribution</groupId>
            <artifactId>distributions-bom</artifactId>
            <version>1.9.4</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>


Add the following dependencies to the <dependencies> section of the pom.xml file:

XML
 
<dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-api</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-impl</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-api</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-impl</artifactId>
    <scope>runtime</scope>
</dependency>


Configuring TomEE and Adding the MySQL JDBC Driver

To use TomEE as a Maven plugin with the MySQL driver included, add it to the <build> section of the pom.xml file:

XML
 
<build>
    ...
    <plugins>
        <plugin>
            <groupId>org.apache.tomee.maven</groupId>
            <artifactId>tomee-maven-plugin</artifactId>
            <version>8.0.7</version>
            <configuration>
                <context>ROOT</context>
                <libs>mysql:mysql-connector-java:8.0.25</libs>
            </configuration>
        </plugin>
	</plugins>
</build>


Configuring the JDBC Connection

The database configuration is configured as a resource in the server. This article uses TomEE as a Maven Plugin. To configure the database resource, create a new src/main/tomee/conf/tomee.xml file with the following content:

XML
 
<tomee>
    <Resource id="mysqlResource" type="DataSource">
        JdbcDriver com.mysql.jdbc.Driver
        JdbcUrl jdbc:mysql://localhost/jakartaee
        UserName root
        Password password
    </Resource>
</tomee>


Remember to use the correct database user name and password.

Defining a Persistence Unit

Add a new src/main/resources/META-INF/persistence.xml file to define a JPA Persistence Unit that references the database connection resource defined in the previous section:

XML
 
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

    <persistence-unit name="jakarataee-pu" transaction-type="RESOURCE_LOCAL">
        <jta-data-source>mysqlResource</jta-data-source>
        <class>com.example.app.User</class>
    </persistence-unit>

</persistence>


Notice that we are using the name of the connection resource (mysqlResource). We'll implement the User class later.

Implementing an Entity

A JPA Entity is a class that is mapped to a database table. Create a new entity as follows:

Java
 
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Objects;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "email")
    private String email;

    @Column(name = "birth_date")
    private LocalDate birthDate;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public LocalDate getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(LocalDate birthDate) {
        this.birthDate = birthDate;
    }
}


JPA defines annotations that are used to match database tables, columns, and other objects to Java classes, fields, and methods.

Creating and Using a Repository Interface

Add the following interface:

Java
 
import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;

@Repository
public interface UserRepository extends EntityRepository<User, Integer> {
}


You don't have to implement this interface. Apache DeltaSpike creates objects of this type at run time. The EntityRepository interface defines useful methods to access the database. You can also add custom query methods using a name convention to let Apache DeltaSpike generate the queries for you.

Creating an EntityManager

Apache DeltaSpike needs an EntityManager produced through a CDI producer. Add the following class to the project:

Java
 
import javax.enterprise.inject.Disposes;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

public class EntityManagerProducer {

    @PersistenceUnit(name = "jakarataee-pu")
    private EntityManagerFactory emf;

    @Produces // you can also make this @RequestScoped
    public EntityManager create() {
        return emf.createEntityManager();
    }

    public void close(@Disposes EntityManager em) {
        if (em.isOpen()) {
            em.close();
        }
    }
}


Create a View With Vaadin

You can use the repository from any part of the application. For example, you can create a Vaadin view that shows the number of users in the database as follows:

Java
 
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.Route;

import javax.inject.Inject;

@Route("")
public class MainView extends VerticalLayout {

    @Inject
    public MainView(UserRepository userRepository) {
        Long count = userRepository.count();
        Notification.show("Users: " + count);
    }

}


Running the Application

Run the application using Maven as follows:

Plain Text
 
mvn package tomee:run


Point your browser to http://localhost:8080 and you should see a notification:

Running the Application in Maven


Database connection MySQL Web application

Opinions expressed by DZone contributors are their own.

Related

  • Building and Integrating REST APIs With AWS RDS Databases: A Node.js Example
  • Java EE 6 Pet Catalog with GlassFish and MySQL
  • Non-blocking Database Migrations
  • The Complete Tutorial on the Top 5 Ways to Query your Relational Database in JavaScript - Part 1

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!