Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Easy database access with Apache DeltaSpike
Alejandro Duarte
Alejandro Duarte

Posted on

     

Easy database access with Apache DeltaSpike

Apache DeltaSpike is a project that includes several modules for increased productivity when developing Java applications that use CDI (from theJakarta EE specifications). This tutorial shows how to set up a MySQL database, define a connection resource, configure JPA, and use the Data module of Apache DeltaSpike to access the database.

You can watch a version of this tutorial onYouTube if you prefer:

Setting up the database

We need something to play with, so let's connect to MySQL: and create a database with a table in it:

mysql-uroot-pcreatedatabasejakartaee;usejakartaeeCREATETABLEusers(idINTNOTNULLAUTO_INCREMENT,emailVARCHAR(255),birth_dateDATE,PRIMARYKEY(id));
Enter fullscreen modeExit fullscreen mode

Let's also insert some sample data:

INSERTINTOusers(email,birth_date)VALUES("test1@test.com","2000-10-15");INSERTINTOusers(email,birth_date)VALUES("test2@test.com","2001-11-16");INSERTINTOusers(email,birth_date)VALUES("test3@test.com","2002-12-17");
Enter fullscreen modeExit fullscreen mode

Setting up the connection in the server

When you develop a Jakarta EE (or Java EE) application you deploy it to a compatible server. There are many Jakarta EE implementations available. For example Eclipse GlassFish, Oracle WebLogic Server, WildFly, Apache TomEE, Payara Server, IBM WebSphere Liberty, JBoss Enterprise Application Platform, and others. Configurations are done in different ways depending on the server you use. This includes database connections.

In Jakarta EE compatible implementations (or servers) you can define resources such as database connection pools using graphical user interfaces or configuration files. This allows you to decouple the resource definition from the application code, which makes sense, for example, if you realize that you most likely use different databases in your development machine and the production environment. In this tutorial, we'll use Apache TomeEE as a Maven plugin. This is useful during development because you don't have to manually download and install the server making it easier to set up the development environment.

You can add the Apache TomEE Maven plugin in section of thepom.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>
Enter fullscreen modeExit fullscreen mode

Notice how we also add the MySQL JDBC driver dependency to the configuration of the TomEE Maven plugin.

To define the connection resource for the TomEE server, create a newtomee.xml configuration file inside thesrc/main/tomee/conf/ directory. Place the following content in the new file:

<tomee><Resourceid="mysqlResource"type="DataSource">        JdbcDriver com.mysql.jdbc.Driver        JdbcUrl jdbc:mysql://localhost/jakartaee        UserName root        Password password</Resource></tomee>
Enter fullscreen modeExit fullscreen mode

Replace the username and password accordingly.

With all this in place, the server is able to create a connection pool that can be referenced by name (mysqlResource) in the application code.

Referencing the database resource from the application code

The first thing we need is a Persistence Unit, which defines a collection of classes (or entities) managed by anEntityManger (that we'll create later), and a data source (the database connection). Create a newpersistence.xml file in thesrc/main/resource/META-INF/ directory and add the following to the file:

<?xml version="1.0" encoding="UTF-8" ?><persistencexmlns="http://java.sun.com/xml/ns/persistence"version="1.0"><persistence-unitname="jakarataee-pu"transaction-type="RESOURCE_LOCAL"><jta-data-source>mysqlResource</jta-data-source><class>com.example.app.User</class></persistence-unit></persistence>
Enter fullscreen modeExit fullscreen mode

As you can see, we are using the name of the database resource we defined in the TomEE server. A production server should define a data source with the same name so you don't have to worry about the configuration details of the database when you deploy the application. As long as there's a data source with the namemysqlResoure, the application will be able to connect to it.

Using Apache DeltaSpike Data

The Data module of Apache DeltaSpike allows us to define repository interfaces with query methods without having to implement them. Let's take advantage of this.

First, add the dependencies to thepom.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><dependencies><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></dependencies>
Enter fullscreen modeExit fullscreen mode

Then, create a CDI producer that creates newEntityManager instances used by Apache DeltaSpike:

importjavax.enterprise.inject.Disposes;importjavax.enterprise.inject.Produces;importjavax.persistence.EntityManager;importjavax.persistence.EntityManagerFactory;importjavax.persistence.PersistenceUnit;publicclassEntityManagerProducer{@PersistenceUnit(name="jakarataee-pu")privateEntityManagerFactoryemf;@Produces// you can also make this @RequestScopedpublicEntityManagercreate(){returnemf.createEntityManager();}publicvoidclose(@DisposesEntityManagerem){if(em.isOpen()){em.close();}}}
Enter fullscreen modeExit fullscreen mode

Notice how we used the name of the Persistence Unit we previously defined in thepersistence.xml file.

Now, implement theUser entity mapped to theusers SQL table:

importjavax.persistence.*;importjava.time.LocalDate;importjava.util.Objects;@Entity@Table(name="users")publicclassUser{@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name="id")privateIntegerid;@Column(name="email")privateStringemail;@Column(name="birth_date")privateLocalDatebirthDate;@Overridepublicbooleanequals(Objecto){if(this==o)returntrue;if(o==null||getClass()!=o.getClass())returnfalse;Useruser=(User)o;returnObjects.equals(id,user.id);}@OverridepublicinthashCode(){returnObjects.hash(id);}publicIntegergetId(){returnid;}publicvoidsetId(Integerid){this.id=id;}publicStringgetEmail(){returnemail;}publicvoidsetEmail(Stringemail){this.email=email;}publicLocalDategetBirthDate(){returnbirthDate;}publicvoidsetBirthDate(LocalDatebirthDate){this.birthDate=birthDate;}}
Enter fullscreen modeExit fullscreen mode

Finally, add the following repository interface:

importorg.apache.deltaspike.data.api.EntityRepository;importorg.apache.deltaspike.data.api.Repository;@RepositorypublicinterfaceUserRepositoryextendsEntityRepository<User,Integer>{}
Enter fullscreen modeExit fullscreen mode

We don't need to implement this interface. Instead, Apache DeltaSpike Data will create instances of this type and dynamically add query methods to it at runtime. In fact, theUserRepository interface inherits useful methods already. For example, we can create aVaadin Flow view that uses this repository to show a notification in the browser with the count of users in the database:

importcom.vaadin.flow.component.notification.Notification;importcom.vaadin.flow.component.orderedlayout.VerticalLayout;importcom.vaadin.flow.router.Route;importjavax.inject.Inject;@Route("")publicclassMainViewextendsVerticalLayout{@InjectpublicMainView(UserRepositoryuserRepository){Longcount=userRepository.count();Notification.show("Users: "+count);}}
Enter fullscreen modeExit fullscreen mode

You can run the application usingmvn package tomee:run and request it athttp://localhost:8080. Here's a screenshot:

A Vaadin Flow view connected consuming data from MySQL through an Apache DeltaSpike repository

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software Engineer · Published author · Developer Relations Engineer at MariaDB
  • Location
    Finland
  • Education
    National University of Colombia
  • Work
    Developer Relations Engineer at MariaDB
  • Joined

More fromAlejandro Duarte

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp