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.
Join the DZone community and get the full member experience.
Join For FreeThis 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:
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:
create database jakartaee;
use jakartaee
Create a new table as follows (the statement is executed once you end a line with a semicolon):
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):
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:
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:
<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:
<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:
<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:
<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 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:
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:
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:
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:
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:
mvn package tomee:run
Point your browser to http://localhost:8080 and you should see a notification:
Opinions expressed by DZone contributors are their own.
Comments