003-spring-data-elasticsearch 3.0.0.0 Use "one"-spring-data introduction, crudrepository,pagingandsortingrepository, etc.

Source: Internet
Author: User
Tags deprecated iterable

0. Overview

The Spring Data Elasticsearch project provides integration with the Elasticsearch search engine. The key functional area of Spring data Elasticsearch is a Pojo central model for interacting with elastichsearch documents and easily writing a repository-style data access layer.

0.1. Main functions

The 1.Spring configuration supports XML namespaces that use Java-based @configuration classes or ES client instances.

2.ElasticsearchTemplate help class to improve productivity in performing common ES operations. Includes an integrated object mapping between the document and the Pojo.

3. Feature-rich object mapping integrates with spring's transformation Services

4. Automatic implementation of the Repository interface, including support for custom find[Finder] methods.

5.CDI Support Repository

Maven using the previous section has explained

0.2. Document Description

See Address: https://docs.spring.io/spring-data/elasticsearch/docs/3.0.4.RELEASE/reference/html/

0.3. Meta Data address

Version Control-https://github.com/spring-projects/spring-data-elasticsearch
Bugtracker-https://jira.spring.io/browse/dataes
Release Repository-https://repo.spring.io/libs-release
Milestone Repository-https://repo.spring.io/libs-milestone
Snapshot Repository-https://repo.spring.io/libs-snapshot
Git:https://github.com/spring-projects/spring-data-elasticsearch
Official Release Notes: https://projects.spring.io/spring-data-elasticsearch/

One, Spring Data repositories

This section information is from the Spring Data Commons module and supports the Java Persistence API (JPA) module

1.1. Core concept

Crudrepository provides complex CRUD functionality for the entity classes being managed.

Example one, Crudrepository interface "basically is literally meaning"
 Public InterfaceCrudrepository<t, IDextendsSerializable>extendsRepository<t, id> {  <sextendsT>s Save (s entity); Optional<T>FindByID (ID primaryKey); Iterable<T>FindAll (); Longcount (); voidDelete (T entity); BooleanExistsbyid (ID primaryKey); //... more functionality omitted.}
View Code

Based on the Crudrepository interface, there are also some extension interfaces JpaRepository or MongoRepository . Elasticsearchcrudrepository and so on. These interfaces extend the Crudrepository interface and provide the functionality of the underlying persistence technology as well as the fairly common persistence technology-agnostic interface.

Example Two, pagingandsortingrepository

There is a pagingandsortingrepository abstraction on top of crudrepository, which adds some additional ways to simplify paging access to entities:

 Public Interface extends Serializable>  extends crudrepository<t, id> {  iterable<T> findAll ( Sort sort);  Page<T> findAll (pageable pageable);}
View Code

Second page of a user with a page size of 20

// ... get access to a bean page<user> users = Repository.findall (new pagerequest (1, 20));
Example three, derived count query

In addition to the Query method, query derivation for count and delete queries is available.

Interface extends Crudrepository<user, long> {  Long  countbylastname (String lastname);}
View CodeExample IV, derived delete query
Interface extends Crudrepository<user, long> {  Long  deletebylastname (String lastname);  List<User> removebylastname (String lastname);}
View Code1.2. Query method

Standard CRUD feature repositories are typically queried on the underlying data store. Using spring Data, declaring these queries into a four-step process:

1. Declare an interface that extends repository or its subinterfaces and enter it into the domain class and ID type that it will process.
Interface extends Repository<person, long> {...}
2, declare the query method on the interface.
Interface extends Repository<person, long> {  List<Person> findbylastname (String lastname);}
3. Set Spring to create proxy instances for these interfaces. by Javaconfig:
Import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories class Config {}

or XML configuration

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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:repositoriesBase-package= "Com.acme.repositories"/></Beans>
View Code4. Get the injected resource pool instance and use it.
class someclient {  privatefinal  personrepository repository;  Someclient (Personrepository repository) {    this. Repository = repository;  }    void dosomething () {    List<Person> persons = Repository.findbylastname ("Matthews");}  }

For the above four steps, the following instructions

1.3. Define Repository Interface

First define a domain class specific repository interface. The interface must extend repository and type into the domain class and ID type. If you want to extend the Crud method for this domain type, expand crudrepository instead of repository.

1.3.1, defining custom Generic Repository

The custom storage interface expands Repository,crudrepository or pagingandsortingrepository. Or, if you do not want to extend the spring data interface, you can also use @repositoryde?? Finition Comment Your repository interface. Extension Crudrepository exposes a complete set of methods to manipulate your entities. If you want to choose an exposed method, simply copy the content exposed from crudrepository to your domain repository.

example, selectively exposing crud methods

@NoRepositoryBean Interface extends extends Repository<t, id> {  Optional<T> FindByID (ID ID);   extends T> S Save (S entity);} Interface extends Mybaserepository<user, long> {  User findbyemailaddress (EmailAddress emailaddress);}
View Code

In the first step, a common basic interface is defined for all the domain repositories, and the FindByID (...) is exposed. ) and save (...). )。 These methods will be routed to the underlying repository implementation of the store that spring data provides for your choice, for example, in the case of JPA Simplejparepository, because they match the method signature in Crudrepository. As a result, userrepository can now save users, find individual users by ID, and trigger queries through their e-mail addresses to find users.

Note that the intermediate repository interface uses @norepositorybean annotations. Be sure to add the comment to all repository interfaces that spring data should not create an instance at run time.

1.3.2, empty handling repository methods

Starting with Spring Data 2.0, the repository Crud method that returns a single aggregate instance uses Java 8 's optional to indicate potential missing values. In addition, Spring data supports the return of other wrapper types on the Query method:

Com.google.common.base.Optionalscala.Optionio.vavr.control.Optionjavaslang.control.Option (deprecated as Javaslang is deprecated)

Or the query method can choose not to use the wrapper type. See the return value for details

nullability annotations

You can use the Spring Framework's nullability annotations to represent the nullable constraints of a repository method. They provide a tool-friendly approach and select invalid checks at run time:

@NonNullApi – The default behavior for the package level to declare parameters and return values is to not accept or generate null values.

@NonNull – for a parameter or return value, the parameter or return value cannot be null (the parameter and return value do not require @nonnullapi).

@Nullable – Used for parameters or return values that can be empty.

Spring Annotations Use the JSR 305 comment for meta comments, and the JSR 305 Comment allows tool vendors like Idea,eclipse or Kotlin to provide empty security support in a generic way without the need for hard-coded support for spring annotations. In order to enable run-time checking of nullable constraints on query methods, you need to use spring's @nonnullapi in Package-info.java to activate the non-nullability of the package level:

Example

@org. Springframework.lang.NonNullApi  Package com.acme;

Once a non-empty default is ready, the Repository Query method call validates the nullability constraint at run time. An exception is thrown when NULL is returned, and you can use nullable annotations

//set a non-empty PackageCom.acme; Importorg.springframework.lang.Nullable;InterfaceUserrepositoryextendsRepository<user, long> {//if the executed query does not produce a result, emptyresultdataaccessexception will be thrown. IllegalArgumentException is thrown when the EmailAddress passed to the method is emptyUser getbyemailaddress (EmailAddress emailaddress); //if the executed query does not produce a result, NULL is returned. Also accepts NULL as the value of the EmailAddress. @Nullable User findbyemailaddress (@Nullable emailaddress emailadress); //if the executed query does not produce a result, Optional.empty () is returned. IllegalArgumentException is thrown when the EmailAddress passed to the method is empty. Optional<user>findoptionalbyemailaddress (EmailAddress emailaddress);}
View Code1.3.3, using the repository with multiple spring data modules

Using a unique spring data module in your application makes things simple, so all repository interfaces within the defined scope are bound to the Spring data module. Sometimes applications need to use multiple spring data modules. In this case, the repository definition requires a distinction between persistence techniques. Spring data enters the strict repository configuration mode because it detects multiple repository factories on the classpath. Strict configuration requires the details of the repository or domain class to determine the spring data module bindings defined by the repository:

1. If the repository definition extends the module-specific repository, it is a valid candidate for a particular spring data module.

2. If the domain class is annotated with a module-specific type comment, it is a valid candidate for a particular spring data module. The Spring Data module accepts third-party annotations (such as JPA @entity) or provides its own annotations for Spring data mongodb/spring data elasticsearch, such as @document.

See Original document: Address

003-spring-data-elasticsearch 3.0.0.0 Use "one"-spring-data introduction, crudrepository,pagingandsortingrepository, etc.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.