Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize the Repository interface for Spring Data JPA

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to customize the Repository interface for Spring Data JPA". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "Spring Data JPA how to customize the Repository interface"!

Custom Repository interface

To define a repository interface, you first need to customize a Repository interface specific to the entity class. The interface must extend Repository and specify its type as entity class and ID type of entity class.

If you want to open the CRUD method for this entity class resource type, directly inherit CrudRepository instead of Repository.

Repository interface definition

Usually, your repository interface extends Repository, CrudRepository, or PagingAndSortingRepository.

If you don't want to extend the Spring Data interface, you can also annotate your repository interface with @ RepositoryDefinition.

Inheriting the CrudRepository interface exposes a complete set of CRUD methods to manipulate your entity class objects. If you want to decide which methods to expose, you can copy the methods you want to expose from CrudRepository to your custom repository interface.

The above operations allow you to define your own repository interface abstraction based on the Spring Data Repositories functions provided.

The following example shows how to selectively expose some specified CRUD methods (in this case, findById and save interface methods).

Selective exposure specifies the CRUD method for others to use

@ NoRepositoryBeaninterface MyBaseRepository extends Repository {Optional findById (ID id); S save (S entity);} interface UserRepository extends MyBaseRepository {User findByEmailAddress (EmailAddress emailAddress);}

In the previous example, we defined a common basic interface for all repository and exposed findById (...) And save (…) Method.

These methods are routed to the underlying repository implementation of your chosen store provided by Spring Data (for example, if you use JPA, the implementation is SimpleJpaRepository) because they are consistent with the method signature in CrudRepository. So UserRepository can now save users, find individual users through ID, and trigger queries to find user objects by e-mail address.

@ NoRepositoryBean needs to be added to the custom intermediate repository interface. Note, however, that this annotation must not be added to all repository interfaces where Spring Data needs to create instances dynamically at run time.

Like the sample code above

-MyBaseRepository is the intermediate repository interface. We need to use it to define which CRUD methods are open to the public, and we need to add the @ NoRepositoryBean annotation, which means a tag to tell JPA not to create a bean object for this interface.

This @ NoRepositoryBean is used on the intermediate repository interface, but the specific repository interface is derived from the intermediate interface, corresponding to the above sample code is the UserRepository interface. Do not add @ NoRepositoryBean annotation on this interface. If added, the bean object of this UserRepository interface will not be injected into the container.

Use the Repository interface

Using the Repository interface in multiple Spring Data modules

Using a unique Spring Data module in your application makes things easy because all repository interfaces within the scope of the definition are bound to the Spring Data module. Sometimes an application needs to use more than one Spring Data module. In this case, the repository definition must distinguish between persistence techniques. When it detects multiple repository factory under the classpath-like path, Spring Data enters strict respository configuration mode. Strict configuration uses the details of respository or domain classes to determine the Spring Data module bindings defined by respository.

If the repository definition extends the repository for a particular module, it is a valid candidate for a particular Spring Data module.

If a domain class is annotated with a type annotation for a particular module, it is a valid candidate for a particular Spring Data module. The Spring Data module accepts third-party annotations (such as JPA's @ Entity) or provides its own annotations (such as Spring Data MongoDB and Spring Data Elasticsearch's @ Document).

The following example shows a repository (JPA in this case) that uses a specific module interface.

Example 1. Using the repository definition of the module-specific interface

Interface MyRepository extends JpaRepository {} @ NoRepositoryBeaninterface MyBaseRepository extends JpaRepository {… } interface UserRepository extends MyBaseRepository {... }

MyRepository and UserRepository extend JpaRepository at their type level. They are valid candidates for Spring Data JPA modules.

The following example shows a repository interface that uses a common interface.

Example 2. Use the repository definition of the common interface

Interface AmbiguousRepository extends Repository {... } @ NoRepositoryBeaninterface MyBaseRepository extends CrudRepository {… } interface AmbiguousUserRepository extends MyBaseRepository {... }

AmbiguousRepository and AmbiguousUserRepository extend only Repository and CrudRepository in their type hierarchy. While this is good when using a unique Spring Data module, multiple modules cannot tell which particular Spring Data these repository interfaces should be bound to.

The following example shows a repository interface that uses annotated domain classes.

Example 3. Use the repository definition of the annotated domain class

Interface PersonRepository extends Repository {... } @ Entityclass Person {… } interface UserRepository extends Repository {... } @ Documentclass User {… }

PersonRepository refers to Person, which is annotated by the @ Entity annotation of JPA, so this repository interface obviously belongs to Spring Data JPA. UserRepository refers to User, which is annotated by the @ Document annotation of Spring Data MongoDB.

The following bad example shows a repository interface for a domain class that uses mixed annotations.

Example 4. Repository definition of domain classes using mixed annotations

Interface JpaPersonRepository extends Repository {... } interface MongoDBPersonRepository extends Repository {... } @ Entity@Documentclass Person {… }

This example shows a domain class that uses both JPA and Spring Data MongoDB annotations. It defines two repository interfaces: JpaPersonRepository and MongoDBPersonRepository. One for JPA and the other for the use of MongoDB. Spring Data is no longer able to distinguish between these repository interface libraries, which results in undefined behavior.

Repository interface type details and differentiated domian class annotations are used for strict repository interface configuration to identify repository interface candidates for a particular Spring Data module. It is possible to use specific annotations of multiple persistence techniques on the same domain type, and the domian type can be reused in multiple persistence techniques. However, Spring Data can no longer identify a unique module to bind the repository interface.

The last way to distinguish repository is by scanning the underlying package of the repository interface. The base package defines the starting point for scanning the repository interface definition, which means that the definition of the repository interface is placed in the appropriate package. By default, annotation-driven configurations use packages of configuration classes. The base package in a XML-based configuration is mandatory.

The following example shows the configuration of an annotation-driven basic package.

Example 5. Annotation-driven basic package configuration

@ EnableJpaRepositories (basePackages = "com.acme.repositories.jpa") @ EnableMongoRepositories (basePackages = "com.acme.repositories.mongo") public class Configuration {} so far, I believe you have a better understanding of "Spring Data JPA how to customize the Repository interface". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report