About the book
Introduced
About this guide
Preface to Chapter I.
Chapter II New and noteworthy points
Chapter III Project Dependencies
The fourth chapter uses spring Data repositories
4.1 Core Concepts
4.2 Query methods
4.3 Defining interfaces for repository
4.4 Defining query methods
4.5. Create a Repository instance
Spring Data JPA Reference Guide Chinese
Read address: https://www.gitbook.com/book/ityouknow/ Spring-data-jpa-reference-documentation/details; the
Spring Data JPA Reference Guide is currently being translated and, for the sake of understanding, we will also add our own views and examples, and will not completely copy the translation, I hope you understand and welcome everyone to join and perfect. If found not fluent or ambiguous place, can be pointed out in the comments, we will promptly correct.
GitHub managed Address: https://github.com/ityouknow/spring-data-jpa-reference-documentation;
Original address: https:// docs.spring.io/spring-data/jpa/docs/current/reference/html/;
We will open the right to each of the participating partners (translation or proofreading), please contact the email in advance [email protected]; Welcome to the JPA Exchange Group, group number: 592638519; Welcome to the JPA Translation QQ Group, group number: 567323266; It is recommended to use Gitbook Editor (https://www.gitbook.com/editor). How to participate: Any questions are welcome to contact me directly [email Protected] . Gitbook provides a great online editing function, so students who want to contribute can contact me directly to apply for permission! License this work is licensed under the Apache License 2.0 International Licensing agreement. Please observe the above license agreement when propagating this document. For more details on this license, refer to: http://www.apache.org/licenses/LICENSE-2.0
Contributors list
Members |
Contact information |
Github |
Ityouknow |
[Email protected] |
Github |
Introduced
It's a pleasure to introduce spring data JPA, a data-friendly standard package that we think is a leap forward in building technology in the Java (JVM) world. Spring DATAJPA provides the ability to manipulate database-standard encapsulation like an object
About this guide
This user guide is still not perfect, as is the case with Springdata JPA, which is still being upgraded. In this guide, some of the features of spring data JPA are not fully displayed. Some of the explanations are not very clear either, or assume that you know more about Springdata JPA. We need your help to refine this guide. You can find more information on perfecting this guide on the Springdata JPA website.
Preface to Chapter I.
1. Project Information
Version Control-HTTP://GITHUB.COM/SPRING-PROJECTS/SPRING-DATA-JPA
Bugtracker-https://jira.spring.io/browse/datajpa
Version Library-Https://repo.spring.io/libs-release
Milestone Library-Https://repo.spring.io/libs-milestone
Snapshot Repository-Https://repo.spring.io/libs-snapshot
Chapter II New and noteworthy points
2.1. New feature points for Spring Data JPA 1.10
1. Support for using projections (mapping) in query methods to get more granular information about objects
2. Support for querying by instance
3. Add the following annotations: @EntityGraph, @Lock, @Modifying, @Query, @QueryHints and @Procedure
4. Set Expressions support contains keywords
5. Attributeconverters Forzoneid of JSR-310 and THREETENBP.
6. Upgrade to QUERYDSL 4, Hibernate 5, OpenJPA 2.4 Andeclipselink 2.6.1
2.2. Spring Data JPA 1.11New feature points for
1. Improved compatibility with Hibernate5.2
2. Support any matching pattern queried by the instance
3. Optimize paging query
4. Support for using exists mappings in query derivation
Chapter III Project Dependencies
Since spring data relies on many different components, most of which have different version numbers, the simplest way to find compatibility is to take advantage of our defined BOM templates, where you can define such fragments in the Pom file in a MAVEN project < Dependencymanagement/> Example 1. Using the version published by spring data in the BOM
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-releasetrain</artifactId>
<version>${release-train}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
The most recently released version is KAY-SR1. The names are sorted alphabetically by ascending order, and the latest available list is here. The naming format for the version is: ${name}-${release}, where release is one of the following 5 types:
1. Build-snapshot-The latest snapshot
2. M1, M2 etc.-Milestones
3. RC1, RC2 etc.-New version Pre-release
4. Release-Officially released version
5. SR1, SR2 etc.-Service Version
We can see how to use the BOM template in the spring data using BOM link. At this point, you do not need to add a version number in the module reference to JPA, as follows.
Example 2. Declaring a JPA module reference
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
<dependencies>
3.1 using springboot to manage dependencies
Spring Boot has selected the latest version, if you want to update to the latest version, just configure Spring-data-releasetrain.version Select a different version to use.
3.2 Spring framework
The current spring data template relies on the Spring framework 5.0.1 release or higher, or the version of the bug that was fixed in the previous version, but it is recommended to use the latest version.
The fourth chapter uses Springdata repositories
The purpose of Spring Data repositories is to use very little code to implement database access for a variety of persistent layers.
Spring data repository file and your module layer
This chapter explains the core concepts of spring and the interface data repository. This chapter information is from the Spring Data Universal module, which uses the configuration and code sample Java Persistence API (JPA) modules. The module you are using is equivalent to adjusting the XML namespace declaration and extension type. The namespace reference covers the XML configuration (all of which are supported by the Spring data module using the Library API), and the library query keyword covers the abstract methods supported by the Query keyword library. You can find detailed information about the specific features of the module layer in the relevant sections of this guide.
4.1Core Concepts
The core interface of the Spring data library is Repository. It uses the domain class to manage the ID type in the domain class as the type parameter. This interface is primarily a markup interface that relies on specific types of operations and helps you discover interfaces, Crudrepository provides rich crud capabilities to manage entity classes.
Example 3. Crudrepository interface
Public interface crudrepository<t, ID extends serializable> extends Repository<t, id> {
<s extends t> S Save (sentity); (1)
T FindOne (ID primaryKey); (2)
Iterable<t> FindAll (); (3)
Long count (); (4)
void Delete (T entity); (5)
Boolean exists (ID PrimaryKey); (6)
... more functionality omitted.
}
(1) Save the specified entity.
(2) returns the entity with the specified ID.
(3) returns all entities.
(4) Returns the number of entities.
(5) Delete the given entity.
(6) Indicates whether an entity with a specified ID exists.
We also offer persistent technology-specific abstractions such as: Jparepository or mongorepository. These interfaces inherit from crudrepository and implement certain functions. Crudrepository has an pagingandsortingrepository abstraction that adds additional methods to simplify paging access to entities:
Example 4:pagingandsortingrepository
Public interface pagingandsortingrepository<t, ID extends serializable> extends Crudrepository<t, id> {
Iterable<t> findAll (sort sort);
Page<t> findAll (pageable pageable);
}
Enter the second page of the user category (the entry for each page is 20), which can be paginated like this
Pagingandsortingrepository<user, long> repository =//... get access to a bean
page<user> users = Repository.findall (new Pagerequest (1, 20));
In addition to query methods, there are statistical queries and delete queries.
Example 5 Query and statistics
Public interface Userrepository extends Crudrepository<user, long> {
Long Countbylastname (String lastname);
}
Example 6 Query and delete
Public interface Userrepository extends Crudrepository<user, long> {
Long Deletebylastname (String lastname);
List<user> Removebylastname (String lastname);
}
4.2Query method
A standard CRUD feature repository typically queries the underlying data store. Springdata these queries into a four-step process:
1. Declare an interface extension library and type it, or one of its child domain classes and ID types, it will handle.
Interface Personrepository extends Repository<user, long> {...}
2, the method of new conditional query on the interface.
Interface Personrepository extends Repository<person, long> {
List<person> Findbylastname (String lastname);
}
3. To create proxy instances for these interfaces, you can pass Javaconfig:
Import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@EnableJpaRepositories
Class Config {}
or XML configuration
<?xml version= "1.0" encoding= "UTF-8"?>
<beans xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xmlns:jpa= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/data/jpa
Http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">
<jpa:repositories base-package= "Com.acme.repositories"/>
</beans>
The JPA namespace used in this example. If you are using abstraction in repository for any other data source, you need to change this appropriate namespace declaration for your enclosure to be supported with JPA, for example: MongoDB. Note that it is not necessary to configure the package through Java variables, which are automatically declared by default next to the class of the annotation. Custom package scans can use the Basepackage property, and specific libraries can use @Enable to annotate.
4. Get repository instance injected and use it.
public class Someclient {
@Autowired
Private personrepositoryrepository;
public void dosomething () {
list<person> persons =repository.findbylastname ("Matthews");
}
}
The down sections explain each step in detail.
4.3DefinedRepositoryThe interface
You first need to define an interface for an entity class, the interface must inherit Repository and enter the entity type and ID type, and if you need to use a crud method, you can use Crudrepository instead of Repository.
4.3.1Custom Interfaces
Typically, your repository interface will extend Repository, crudrepository, or pagingandsortingrepository. In addition, if you do not want to inherit the spring data interface, you can also annotate the library interface @RepositoryDefinition. Extended Crudrepository exposes a complete set of methods to manipulate your entities. If you prefer to choose the calling method, simply copy the exposure crudrepository you want to your repository. This allows you to define your own abstraction on the elasticity to provide the functionality of the data repository.
Example 7: Selectively exposing crud methods
@NoRepositoryBean
Interface Mybaserepository<t, ID extends serializable> extends Repository<t, id> {
T FindOne (ID ID);
T Save (t entity);
}
Interface Userrepository extends Mybaserepository<user, long> {
User findbyemailaddress (EmailAddress emailaddress);
}
The first step you define is a public-base interface that provides FindOne (...) And the Save (...) method, these methods will be introduced into the implementation class of the spring data of your choice, such as Jpa:simplejparepository, because they match the Crudrepository method signature, the
With userrepository will have saveusers function and FindOne (...) function, of course, also has the function of findbyemailaddress.
Note that if @NoRepositoryBean annotations are added to the intermediate repository interface, verify that all of your repository have added this annotation at this time spring Data will not create an instance.
4.3.2.UseSpringdataMultiple modules to createrepositories
Using the unique spring data module is very simple in the application, but sometimes we need more springdata modules, such as the need to define a repository to differentiate between two different persistence technologies, if multiple repository are found in class path , Springdata will make strict configuration restrictions to ensure that each repository or entity decides to bind the Spring data module:
1, if the repository definition inherits the special repository, he is a special spring data module
2. If the entity annotations a special declaration, it is a special spring data module, the Springdata module receives a third-party declaration (ex: JPA ' S@entity) or provides a spring datamonggodb/spring data Elasticsearch's @Document.
Example 8. Custom Special Repostity
Interface Myrepository extends Jparepository<user, long> {}
@NoRepositoryBean
Interface Mybaserepository<t, ID extends serializable> extends Jparepository<t, id> {
...
}
Interfaceuserrepository extends Mybaserepository<user, long> {
...
}
Myrepository and userrepository inherit from Jparepository in this hierarchy is a legitimate alternative to the Springdata JPA module
Example 9. Use a generic interface definition repository
Interface Ambiguousrepository extends Repository<user, long> {
...
}
@NoRepositoryBean
Interface Mybaserepository<t, ID extends serializable> extends Crudrepository<t, id> {
...
}
Interface Ambiguoususerrepository extendsmybaserepository<user,long> {
...
}
Ambiguousrepository and Ambiguoususerrepository only inherit from Repository and crudrepostory at their level. It is perfect when they use a springdata module, but if the multi-module springdata is used, spirng cannot distinguish between the ranges of each repository.
Example 10. Use entity class annotations to define the scope of use of repository
Interface Personrepository extends Repository<person, long> {
...
}
@Entity
public class Person {
...
}
Interface Userrepository extends Repository<user, long> {
...
}
@Document
public class User {
...
}
The person uses the @Entity annotation personrepository to reference it, so the repository uses Spingdata JPA clearly. The User that userrepository refers to declares @Document surface this warehouse will use the Springdata MongoDB module.
Example 11. Use mixed annotations to define warehouses
Interface Jpapersonrepository extends Repository<person, long> {
...
}
Interface Mongodbpersonrepository extends Repository<person, long> {
...
}
@Entity
@Document
public class Person {
...
}
In this example, the entity class person Two annotations are used to indicate that the entity class can be used for both jpapersonrepository and Mongodbpersonrepository ' ', springdata cannot determine that the warehouse type leads to undefined behavior. The repository inherits or uses annotations to determine the use of the Spring data module. With multiple annotations to the same entity to achieve multiple types of persistence, Spring data is not restricted to binding to only one repostitory. The last way to distinguish between different warehouse types is to use the package path to determine. Warehouses under different package paths use different warehouse types, implemented by declaring annotations in configuration class configurations, or by XML configuration.
Example 12: Use annotations to implement different package paths, using different warehouses
@EnableJpaRepositories (basepackages = "COM.ACME.REPOSITORIES.JPA")
@EnableMongoRepositories (basepackages = "Com.acme.repositories.mongo")
Interface Configuration {}
4.4 Defining query methods
There are two ways to query the repository agent. One is that depending on the method name or the custom query, the options available depend on the actual store. However, based on the corresponding strategy to determine the actual SQL creation, let's look at the selection.
4.4.1.Query Lookup Policy
The following strategies can be addressed by querying the library infrastructure. You can configure the policy namespace through the XML configuration of the Querylookup-strategy property or through the Java configuration of Querylookupstrategy enabled properties ${store} library annotations. Some policies may not support specific data stores. Create tries to build a query method name that can find the query. The usual practice is to put a given set of prefix-prefixed method names and parse methods. Use_declared_query tries to find a declaration query and throws an exception condition. Queries can be defined on annotations. Create_if_not_found (default) combines CREATE and use_declared_query. It looks like a declaration query first, if no claims query is found, it creates a custom name-based query method. This is the default lookup policy, so if you do not use any explicit configuration. It allows quick querying of defined method names, and also custom-tuning these queries by introducing required queries.
2.4.2Create a query
The query Builder mechanism is built into entities that build constrained query libraries. The mechanism with the prefix Findxxby, Readaxxby, Queryxxby, Countxxby, Getxxby automatically resolves the remainder. Further introduction clauses can include expressions such as Distinct settings for different conditions to create a query. However, the first by as a delimiter represents the beginning of the actual standard. In a very basic query, you can define conditions and OR.
Example 13. Create a query based on the method name
Public interface Personrepository extends Repository<user, long>{
List<person> findbyemailaddressandlastname (emailaddressemailaddress, String LastName);
Enables THEDISTINCT flag for the query
List<person> finddistinctpeoplebylastnameorfirstname (stringlastname, String FirstName);
List<person> findpeopledistinctbylastnameorfirstname (stringlastname, String FirstName);
Enabling ignoring case for a individual property
List<person> findbylastnameignorecase (stringlastname);
Enabling Ignoringcase for all suitable properties
List<person> findbylastnameandfirstnameallignorecase (stringlastname, String FirstName);
Enabling Staticorder by for a query
List<person> FINDBYLASTNAMEORDERBYFIRSTNAMEASC (stringlastname);
List<person> Findbylastnameorderbyfirstnamedesc (stringlastname);
}
The parsing method of the actual results depends on your persistent storage creation query. -However, there are some general things to note. Traversal expressions are usually joined by an operator. You can put expressions and and or, between, LessThan (not more than), GreaterThan, like, and so on, these operations may differ for different databases, depending on the reference document method parsing support settings IgnoreCase on the property (For example, Findbylastnameignorecase (...)), or support querying all attributes ignoring case (for example, Findbylastnameandfirstnameallignorecase (...)), ignoring case support for all databases, Other queries refer to the relevant documentation. You can apply a static sort by appending an order by by Datum, which provides a sort (ASC or DESC) for the reference property and direction. Create a query method that supports dynamic ordering and understand the special parameter handling.
4.4.3. Property Expressions
Property expressions can only refer to entities that are directly property-managed, as shown in the previous example. When you create a query, you have ensured that you parse a property of the domain class for real estate management. However, you can also define constraints by traversing nested properties. Suppose a person has an Address with a Zipcode. In this scenario, the name of a method
List<person> Findbyaddresszipcode (ZipCode ZipCode);
Creates an attribute traversal X.address.zipcode. Method execution first interprets the entire section (Addresszipcode) as property and examines the name of the Domain class property (lowercase form). Split the source in the Camel-case section from the right head and tail, trying to find the corresponding property, in our example, split into Addresszip and Code. Split mismatch, the algorithm splits the point to the left (Address, Zipcode) and then continues, in most cases, this algorithm may have errors that you can use to resolve this ambiguity _ in the method name to manually define the traversal point. So our method name will end up like this:
List<person> Findbyaddress_zipcode (ZipCode ZipCode);
If your property name contains an underscore, such as. First_Name underline), it is recommended to use the hump way to avoid.
4.4.4Special parameter handling
To process a parameter query, only the method parameter is defined as already in the example above. In addition to the underlying query will recognize that some specific types of pageable and sort apply dynamic query paging and sorting
Example 14. Use pageable, Slice, and Sort to query
Page<user> Findbylastname (String LastName, pageablepageable);
Slice<user> Findbylastname (String LastName, pageablepageable);
List<user> Findbylastname (String LastName, sort sort);
List<user> Findbylastname (String LastName, pageablepageable);
The first method allows you to dynamically add paging through a org.springframework.data.domain.Pageable instance in the static definition query of your query method. The paging class knows the total number of elements and available pages. It uses the base library to trigger a statistical query to calculate all the totals. Since this query can be expensive for the store, you can use slice instead. Slice only knows if the next slice is available, which is enough for querying big data. The sort options and pagination are handled the same way. If you need to sort, simply add a org.springframework.data.domain.Sort parameter to your method. As you can see, it is also possible to simply return a list, in which case the additional metadata required for the production of the paging instance will not be created (which also means that additional count queries may be required but not necessarily advertised). To find out how many pages are in your query, you need to trigger an extra count query. Follow the defaults to
That this query can be derived from your actual trigger query.
4.4.5.Limit query Results
The results of the query method can be limited by the keyword first or top, which can be used interchangeably. Add a number after top/firest to indicate the maximum number of results returned. If there is no number, the default assumes 1 as the result size. Example 15 limiting the result size with Top and first queries
User Findfirstbyorderbylastnameasc ();
User Findtopbyorderbyagedesc ();
Page<user> queryfirst10bylastname (String lastname,pageablepageable);
Slice<user> Findtop3bylastname (String LastName, pageable pageable);
List<user> Findfirst10bylastname (String LastName, Sortsort);
List<user> findtop10bylastname (String lastname,pageable pageable);
The restriction expression also supports the DISTINCT keyword. For restricting the result set of a query to one instance of wrapper this result is also supported in a optional. If a page or slice is applied to a restricted query page (counting how many pages are available), it can also be applied to limit the results. It is important to note that the limit results of dynamic sorting by the sort parameter allow the method of expression query to be the smallest of "K" and the largest element of "K".
4.4.6.Stream Query Results
The query method can be used to step through the results returned by the stream of Java 8. Instead of simply wrapping the query results in a stream data store that is used to execute the stream, a specific method is stored.
Example 16 stream processing result of query with JAVA8 stream
@Query ("Select u from User u")
Stream<user> Findallbycustomqueryandstream ();
Stream<user> Readallbyfirstnamenotnull ();
@Query ("Select u from User u")
Stream<user> streamallpaged (pageable pageable);
A data stream may wrap the underlying data to store specific resources, so it must be closed after use. You can also manually turn off the data flow using the close () method or the JAVA7 try-with-resources block.
Example 17 operation of a stream in a try-with-resources block
Try (stream<user Stream = Repository.findallbycustomqueryandstream ()) {
Stream.foreach (...);
}
Not all spring data modules currently support stream as the return type
4.4.7. Asynchronous Query Results
@Async
Future<user> findbyfirstname (String firstname); (1)
@Async
Completablefuture<user> findonebyfirstname (String firstname); (2)
@Async
Listenablefuture<user> Findonebylastname (String lastname); (3)
(1) using Java.util.concurrent.Future as the return type
(2) using Java 8java.util.concurrent.completablefuture as the return type
(3) using Org.springframework.util.concurrent.ListenableFuture as the return type
4.5.CreateRepositoryInstance
In this section you create the instance and the bean defined for the repository interface. One way to do this is to use the spring namespace, which is the configuration with each spring data module that supports the storage mechanism, although we generally recommend using the Java configuration style.
4.5.1 XMLConfiguration
Each spring data module contains a repositories element that allows you to simply perform a spring scan based on the base-package definition.
Example 18 using XML to open spring Data repositories
<?xml version= "1.0" encoding= "UTF-8"?>
<beans:beans xmlns:beans= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
Xmlns= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans.xsd
Http://www.springframework.org/schema/data/jpa
Http://www.springframework.org/schema/data/jpa/spring-jpa.xsd ">
<repositories base-package= "Com.acme.repositories"/>
</beans:beans>
Referenced from: https://www.gitbook.com/book/ityouknow/spring-data-jpa-reference-documentation/details
Spring Data JPA (Official document translation)