Hello, this is Yijun@Monday commuter radio.

You will have learned by the end of this article

  • How do I introduce Spring Data JPA into a Spring project

The total read length of this article Is approximately 1800 hours, roughly equivalent to The black Eyed Peas song “Where Is The Love?” .

1. An overview of the

This article will focus on how to introduce Spring Data JPA into your Spring project and fully configure the persistence layer.

2. DAO generated by Spring Data — there is no longer an implementation of DAO

There is a lot of boilerplate code in the design of the DAO layer, which should be simplified. The benefits of this simplification are many: reducing the number of components we need to define and maintain; Maintain consistency of data access patterns; And maintaining configuration consistency.

Spring Data takes this simplification a step further, making it possible to completely remove the DAO implementation. The DAO’s interface is now the only component we need to define explicitly.

To start leveraging JPA’s Spring Data programming model, a DAO interface needs to extend JPA-specific Repository interface JpaRepository. This will enable Spring Data to find the interface and automatically create an implementation for it. By extending the interface, we get CRUD methods available in standard DAOs.

3. Customize access methods and queries

As discussed above, the DAO defines and implements some basic CRUD methods and queries by implementing an interface to Repository.

To define more specific access methods, Spring JPA supports the following options:

  • Just define a new method in the interface
  • Provide JPQL queries by using @Query annotations.
  • Use the more advanced Specification and Querydsl support in Spring Data.
  • Define custom queries using JPA named queries

The third option, Specification and Querydsl support, is similar to the JPA standard but uses a more flexible and convenient API. This makes the entire operation much more readable and reusable. The advantage of this API becomes even more apparent when dealing with a large number of fixed queries, as it is possible to express those queries more succinctly with fewer reusable blocks of code.

The disadvantage of the last option is that it either involves XML or puts the query burden on the entity class.

3.1 Automatic and customized Query

When Spring Data creates a new Repository implementation, it analyzes all the methods defined by the interface and tries to automatically generate queries from method names. While this has some limitations, it is a very powerful and elegant way to define new custom access methods with minimal effort.

We can look at an example. If the entity has a name field and Java Bean standard getter and setter methods, we will define the findByName method in the DAO interface. This will automatically generate the correct query:

public interface IFooDAO extends JpaRepository<Foo, Long> {

    Foo findByName(String name);

}
Copy the code

This is a relatively simple example. The query creation mechanism supports more keywords:

If the parser cannot match this property to the domain object field, we see the following exception.

java.lang.IllegalArgumentException: No property nam found for type class com.jayxu.spring.data.persistence.model.Foo
Copy the code

3.2 User-defined Query

Now let’s look at a custom Query that we will define with the @Query annotation.

@Query("SELECT f FROM Foo f WHERE LOWER(f.name) = LOWER(:name)")
Foo retrieveByName(@Param("name") String name);
Copy the code

4. Transaction configuration

The implementation of the Spring-managed DAO is hidden because we don’t use it directly. However, it is a very simple implementation, SimpleJpaRepository, that defines transaction semantics using annotations.

More specifically, this uses a read-only @Transactional annotation at the class level, and then overrides non-read-only methods. The remaining transaction semantics are default, but these can easily be manually overridden by each method.

4.1 Exception translation is still OK

In Java, we usually use try-catch statements to catch exceptions for exception handling. Sometimes, however, we use try-catch to catch an exception, but instead of doing any exception handling, another exception is thrown. This is called exception translation.

Now the question is: Since Spring Data JPA does not rely on old ORM templates (JpaTemplate, HibernateTemplate) and they have been removed since Spring 5, Can we still get our JPA exceptions translated into Spring’s DataAccess Eption hierarchy?

The answer is, of course we do. Exception translation can still be implemented by using the @repository annotation on the DAO. Richard apparatus can be used after the annotations made Spring Bean container found in all instances of all PersistenceExceptionTranslator told @ Repository Bean, and provide exception translation as before.

Let’s verify the exception translation with an integration test.

@Test(expected = DataIntegrityViolationException.class)
public void givenFooHasNoName_whenInvalidEntityIsCreated_thenDataException() {
    service.create(new Foo());
}
Copy the code

Keep in mind that exception translation is done by proxy. In order for Spring to be able to create proxies around DAO classes, those classes must not be declared final.

5.Spring Data JPA Repository configuration

To activate Spring JPA Repository support, use the @EnableJpaRepositories annotation and specify the package that contains the DAO interface.

@EnableJpaRepositories(basePackages = "com.jayxu.spring.data.persistence.repository") public class PersistenceConfig { . }Copy the code

We can do the same thing with XML configuration.

<jpa:repositories base-package="com.jayxu.spring.data.persistence.repository" />
Copy the code

6.Java or XML configuration

We will discuss in detail how to configure JPA in Spring in a new article. Spring Data also leverages Spring’s support for jPA@Persistencecontext annotations. It uses this to connect the EntityManager to the Spring factory Bean (JpaRepositoryFactoryBean) responsible for creating the actual DAO implementation.

In addition to the configuration already discussed, if we use XML, we also need to include the Spring Data XML configuration.

@Configuration
@EnableTransactionManagement
@ImportResource("classpath*:*springDataConfig.xml")
public class PersistenceJPAConfig {
    ...
}
Copy the code

7.Maven dependencies

In addition to Maven’s JPA configuration, we also need to add spring-data-JPA dependencies.

<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-jpa</artifactId> The < version > 2.4.0 < / version > < / dependency >Copy the code

8. Use Spring Boot

We can also use the Spring Boot Starter Data JPA dependency, which will automatically configure the Data source for us. We need to make sure that the data store we are using is in the classpath. In our example, we have added the H2 in-memory database.

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> The < version > 1.4.200 < / version > < / dependency >Copy the code

Just by making these dependencies, our application is up and running and we can use it for other database operations. The configuration of standard Spring applications is now included in Spring Boot’s automatic configuration. Of course, we can modify the automatic configuration by adding our custom explicit configuration. Spring Boot provides an easy way to do this using properties in the application.properties file.

spring.datasource.url=jdbc:h2:mem:db; DB_CLOSE_DELAY=-1 spring.datasource.username=sa spring.datasource.password=saCopy the code

In this example, we changed the CONNECTION URL and username password.

9. Conclusion

In this article, we introduced the configuration and implementation of the Persistence layer of The Spring Data JPA using XML and Java-based configuration. We discussed how to define more advanced custom queries, as well as the configuration of transactions and the new JPA namespace. Now that Spring can access data in a new and elegant way, try it out.

Thanks for watching yijun@Monday Commuter Radio. If you feel good, quickly give me three support, let’s next period see each other.