27th March 2019

Implementing Repositories in Java SE using DeltaSpike

Repositories are one of my favorite patterns to make an abstraction of the data layer of an application. You may have heard about it if you have ever read an article about Domain Driven Design. Hence in this post I consider you have the basic familiarity with it and will focus mostly on how to implement this pattern in a typical Java SE application by using Apache DeltaSpike data module.

What is Apache DeltaSpike?

Apache DeltaSpike project provides a comprehensive set of CDI extensions each focusing on a specific aspect of a typical application like security, data access, configuration or test. This allows Java developers to focus more on the business part of the application.

Here we’ll try to see how we can use the data module of this library as a basis to implement our repositories. Also in order to have a CDI container in our Java SE application, we’ll incorporate another DeltaSpike module called cdi control. It provides an abstraction layer on top of well known CDI containers like Weld or OpenWebBeans.

The example scenario

We’ll try to keep the scenario as simple as possible and will focus on the implementation details. Therefore we’ll only have a simple Person entity and will try to see how we can save/delete/update and also implement different finders for it. Eventually our final code would be a service class like this:

Adding dependencies

The Apache DeltaSpike has a core module that should always be included. Beside that, you should add a specific module (in this case the data module) to your project as needed. You can check out the whole project at my GitHub repository at https://github.com/moghaddam/javaindeed.

Here are the dependencies for the DeltaSpike core modules (deltaspike version is defined as property on top of the pom file):

and here are the Apache DettaSpike data module dependencies:

Next the cdi control module together with the Weld implementation itself to be used as the CDI container:

Finally the H2 in memory database, its JDBC driver and the Hibernate dependencies should also be added:

Setup CDI and JPA configuration

The CDI container will scan a JAR file only if it could find the beans.xml file in its META-INF folder. So the the next step is to add it to our project:

Next we should add the persistence.xml file to the META-INF folder:

Since it’s an standalone application and we don’t have any application server, we’ll not have a JTA transaction. As can be seen, the value of the “transaction-type” is set to “RESOURCE-LOCAL”.

Adding JPA Entity

Now it’s time to add our Person entity. It has the following basic properties:

  • id
  • firstName
  • lastname
  • creationDate

Setup EntityManager producer

To be able to access the entity manager instance via injection, we should provide a producer method for that. Here we can use the @PersistenceUnitName annotation provided by DeltaSpike jpa module. Basically it scans the classpath and finds all persistence.xml files and then tries to create an instance of EntityManagerFactory for the persistence unit we requested.

By doing so, DeltaSpike knows how to access our entity manager.

Implementing the Repository

To introduce a new repository for an entity, you should have a class or an interface implementing EntityRepository<E, PK extends Serializable> interface. Its type parameters are:

  • T: The entity class that it’s going to manage
  • PK: The type of the primary key of the entity (e.g. Long, Integer, etc.)

Below you can find the list of its methods:

Fortunately there is an abstract class named AbstractEntityRepository implementing this interface which you can extend your repository class from. Also you should remember to annotate the repository class with the @Repository annotation.

You can see here that:

  • The repository is defined as an abstract class. That’s because at runtime, the DeltaSpike picks-up all classes/interfaces marked with @Repository annotation and provides an implementation for them dynamically.
  • The finder method has no implementation. Mainly because the method name follows a naming convention defined by DeltaSpike called Query Method Expression (more on that follows). The actual implementation of the finder method will be generated at runtime based on this naming.

What is Query Method Expression?

It’s a convention to define a method name in such a way that it would be possible for the DeltaSpike to tokenize/parse and create an appropriate JPA query based on it. Here are the the basic rules for naming methods (based on the original documentations):

  • The query method must return an entity, an Optional of an entity, a list of entities or a stream of entities.
  • It must start with the findBy prefix (or related findOptionalBy, findAnyBy, findAll, findFirst or findTop).
  • Followed by a property of the Repository entity and an optional comparator (check the next item). The property will be used in the query together with the comparator. Note that the number of arguments passed to the method depend on the comparator.
  • You can add more blocks of property-comparator which have to be concatenated by a boolean operator. This is either an And or Or
  • You can also use the same way for delete an entity. Basically it must start with the removeBy keyword (or related deleteBy)

For more detailed explanation, check Apache DeltaSpike online documentation.

The main method of the application

Now that we have implemented our Repository, the PersonService class we defined at the beginning of the post should work. So here are the remaining steps that will be covered in our Main class:

  • Bootstrap the CDI container using DeltaSpike CDI container module
  • Get access to the PersonService class via CDI container
  • Call business methods on the service instance
  • Shutdown the CDI container

I’ve added necessary comments to the Java code itself.

Removing an entity

In order to remove an entity, we can still use the method expressions but the prefix would be removeBy. For example to remove a person using lastName property, we can add a method to our repository as:

Summary

What demonstrated in this post is definitely not the best practice or something that would be recommended to be used in production. I was trying to show how easy it would be to setup a project data access layer using DeltaSpike data module. I highly recommend readers to take a look at project’s documentation to know about more advanced features.

Please follow and like us:

You may also like...