Spring Data JPA Instance Query

Source: Internet
Author: User
Tags list of attributes ming
Third. Understanding "Instance query"
 

1. Concept Definition:



In the example above, this creates an "instance" of:example<customer> ex = Example.of (Customer, matcher); We see that the example object, created by customer and Matcher, is easy to explain, and we define some definitions first.



A, Entity object: A Field object that corresponds to a table in the persistence framework, an object that represents a record in a database table, such as the customer object in the previous example. When you build a query condition, an entity object represents the Value section in the query criteria. such as: To query the surname "Liu" customer, the entity object can only store the condition value "Liu".



B, the matching device: The Examplematcher object, which matches the entity object, indicates how to query using the value in the Entity object, which represents the query method, and explains how to check the problem. such as: To inquire the surname "Liu" the customer, namely the name with "Liu" the beginning of the customer, the object represents the "start with a" This query method, as in the above example: Withmatcher ("Name", Genericpropertymatchers.startswith ())



C, Example: The example object, which represents the complete query condition. Created by the Entity object (query condition value) and the match (query mode).



again to understand "instance query", as the name implies, is through an example to query. To query the customer object, the query condition is also a customer object, which, through an existing customer object, is an example of a query and an object that matches this example.






2, Characteristics and constraints:



1, support dynamic query. that is, the number of support query condition is not fixed, such as: There are multiple filters in the customer list, the user when using the "Address" query box entered a value, you need to filter by address, if there is no input value, ignore this filter condition. The corresponding implementation is to set the Address property value to a specific condition value or NULL when constructing the query condition customer object.



2. Filtering condition grouping is not supported. that is, the filter is not supported by or (or) to connect, all the filter search, is a simple layer of the and (and) connection.



3. Only string start/include/end/regular expression matching and other attribute types are supported for exact matching. query, to a matching property (such as name name), can only pass in a filter value, such as customer, for example, to query the surname "Liu" customers, "Liu" This condition value is stored in the Name property of the Customer object that represents the conditional object, for the " Name "Filter also only such a location to store filter values, there is no way to pass in two filter values at the same time. Because of this limitation, some queries can not be supported, for example, to query a time period added to the customer, the corresponding property is Addtime, need to pass in the "Start Time" and "End Time" two criteria, and this query method does not have a location of two values, so there is no way to complete such a query.






Fourth. Key understanding of Examplematcher






1. Factors to be considered


The expression of the query condition, there are two parts, one is the condition value, the second is the query method. Conditional values are stored in entity objects, such as the customer object, and are relatively simple, and when the page passes through the filter value, the property remains the default value when it is deposited into the corresponding attribute. The query method is indicated by the match examplematcher, the situation is relatively complex, the factors to be considered are: (1) The processing of NULL value. When a condition value is null, should this filter be ignored, or should it match a record in the database table where the field value is NULL? (2) Basic types of processing. If the age of the customer object is an int, when the page does not pass in the condition value, it defaults to 0, is a value, then whether to participate in the query? (3) Some property values are ignored. An entity object that has many properties, and whether each attribute participates in filtering? Can I ignore some properties? (4) different filtration methods. Also as a string value, the "name" may want to match exactly, "address" want fuzzy matching, how to do? (5) Case matching. When strings match, sometimes you might want to ignore the case and sometimes not ignore it, how do I do it? 2, five configuration itemsAround the above scenario, 5 configurations are defined in Examplematcher to address these issues.


public class ExampleMatcher {
NullHandler nullHandler; // Null value processing method
StringMatcher defaultStringMatcher; // Default string matching mode
boolean defaultIgnoreCase; // The default case is ignored
PropertySpecifiers propertySpecifiers; // Specific query methods for each property
Set <String> ignoredPaths; // List of ignored properties
...
}


(1)Nullhandler: null value Processing, enumeration type, 2 optional values, include (included), IGNORE (Ignore). Identifies an attribute value (a condition value) that is null for an entity object as a condition, whether it participates in filtering. When the option value is include, the expression still participates in the filter, which matches the record in the database table where the field value is null, and if the value is ignore, the filter is not involved.


(2)Defaultstringmatcher: Default string matching method, enum type, 6 optional values, default (defaults, effect with exact), exact (equal), starting (start match), ending (end match), containing (contains, fuzzy match), Regex (regular expression).    This configuration is valid for all string attribute filters, unless the attribute defines its own matching method in Propertyspecifiers alone. 

(3)Defaultignorecase: The default case is ignored, Boolean, when the value is false, that is, not ignored, the size is not equal.    This configuration is valid for all string property filters, unless the property individually defines its own ignore case in propertyspecifiers. 

(4)propertyspecifiers: Each property-specific query method, describes the individual properties of the query method defined separately, each query method contains 4 elements: attribute name, string matching method, case-insensitive method, property converter. If the property does not have a separate definition of the query, or if an element is undefined (such as a string match), the default value defined in Examplematcher is used, which is the Defaultstringmatcher and    The value of the defaultignorecase.

(5)ignoredpaths: Ignores attribute lists, ignoring properties that do not participate in query filtering.


3. Operation Method


A series of methods are defined in Examplematcher to set these 5 settings, all of which return the Examplematcher object, so the chained programming configuration is supported.




(1) Create a default Examplematcher object.



Defined:



public static examplematcher matching ()



The default configuration is as follows:
A, Nullhandler:ignore. Null value handling: Ignore
B, Defaultstringmatcher:default. Default string matching method: Default ( equality )
C, Defaultignorecase:false. Default case Ignore mode: do not ignore
D, Propertyspecifiers: Empty. Each property is queried in a specific way, empty .
E, ignoredpaths: Empty list. Ignore the list of attributes, empty list .






(2) Change the null value processing mode.



Defined:
Public Examplematcher Withnullhandler(Nullhandler nullhandler)
Public Examplematcher withincludenullvalues()
Public Examplematcher withignorenullvalues()



Produce effect:
Change the configuration item Nullhandler, set to: Specify value, include (included), IGNORE (Ignore).






(3) Change the default string matching method.
Defined:
Public Examplematcher withstringmatcher(stringmatcher defaultstringmatcher)



Produce effect:
Change the configuration item Defaultstringmatcher, set to the specified value.






(4) Change the default case ignore mode.
Defined:
Public Examplematcher withignorecase()
Public Examplematcher Withignorecase(boolean defaultignorecase)



Produce effect:
Change the configuration item defaultignorecase, set to: True, to specify a value.






(5) Add an attribute to the Ignore attribute list.
Defined:
Public Examplematcher withignorepaths(String ... ignoredpaths)



Produce effect:
Change the configuration item ignoredpaths to add one or more properties to the list.






(6) Configuring property-specific query methods



A specific query method for a property that contains 3 information: string matching, case-insensitive, property converters, stored in propertyspecifiers, and Genericpropertymatcher classes to pass configuration information. There are 4 ways to change the configuration, these 4 methods of operation, the internal use of incremental change, that is, if the attribute is not defined as "specific query mode", it will define a, and according to the incoming "non-empty Information" configuration, if already defined, it will be in accordance with the incoming "non-empty Information" to update. If a value is not set for string matching, casing ignore in a specific query method, the default configuration in Examplematcher is used in the query.






A, how to customize the class.



Defined:
Public Examplematcher withmatcher(String PropertyPath, matcherconfigurer<genericpropertymatcher> Matcherconfigurer)



Produce effect:



Add or update the configuration of the attribute "specific query mode" to Propertyspecifiers.



Parameter description:
PropertyPath: To configure the property name for a specific query.
Matcherconfigurer: The custom Class object. The custom class needs to implement the Matcherconfigurer interface, specifying the relevant configuration in the Configurematcher () implementation method of the interface.






B, the direct introduction of Common Properties Query object mode.



Defined:
Public Examplematcher withmatcher(String propertyPath, Genericpropertymatcher genericpropertymatcher)



Produce effect:



Add or update the configuration of the attribute "specific query mode" to Propertyspecifiers.



Parameter description:
PropertyPath: To configure the property name for a specific query.
Genericpropertymatcher: Pass in a generic query object directly. The Examplematcher.genericpropertymatchers tool class provides static methods for commonly used object creation, and all methods return Genericpropertymatcher objects, so chained programming configurations are supported.






In addition: The Genericpropertymatcher class itself provides a number of methods for changing the relevant configuration items.






C, changing the case of ignoring the way



Defined:
Public Examplematcher withignorecase(String ... propertypaths)



Produce effect:
Add or update the "case-insensitive" configuration in the attribute "specific query mode" to Propertyspecifiers:






D, set the property converter



Defined:
Public Examplematcher Withtransformer(String PropertyPath, Propertyvaluetransformer Propertyvaluetransformer)


Produce effect:
Add or update the property converter configuration in the property "specific query mode" to Propertyspecifiers.


Fifth. General INFORMATION






1, about the basic data type.
In the entity object, avoid using the base data type, using the wrapper type. If the base type is already in use,
While this property query does not need to be filtered, it is added to the Ignore list (ignoredpaths).



2, Null value processing method.
The default value is IGNORE (ignore), that is, when the condition value is null, the filter is ignored, and the general business is satisfied with this approach. When you need to query for records in a database table that have a property of NULL, you can set the value to include, and for properties that do not need to participate in the query, you must add to the Ignore list (ignoredpaths), or the data will not be found.



3, the default configuration, special configuration.
By default, when you create a match, the string takes an exact match, does not ignore the case, and you can change the default match by manipulating it to meet the needs of most query criteria, such as changing the string match method to containing (include, Fuzzy match), which is a more common case. Specific query methods are required for individual properties and can be met by configuring the attribute-specific query method.



4. Non-string attributes
As discussed in the constraints, non-string attributes are exact matches, which equals.



5, ignoring the case of the problem.
Ignore the size of the effective or not, is dependent on the database. For example, in a MYSQL database, when the table structure is created by default, the fields are ignored, so this configuration is ignored. If the business needs to be strictly case-sensitive, you can change the database table structure properties to achieve, specifically Baidu.






Sixth. examples of common queries



For example, using the entity object and simulation data in the quick Start, make a list of common queries for easy reference in development.






1, without a horse adapter situation
Requirements: The query address is "Henan province Zhengzhou", and focus on the customer.
Description: You do not need to create a match for the default match when the condition is met.




// Create query condition data object
         Customer customer = new Customer ();
         customer.setAddress ("Zhengzhou, Henan Province");
         customer.setFocus (true);
        
         // Create an instance
         Example <Customer> ex = Example.of (customer);
        
         //Inquire
         List <Customer> ls = dao.findAll (ex);
        
         // output result
         System.out.println ("Amount:" + ls.size ());
         for (Customer bo: ls)
         {
             System.out.println (bo.getName ());
         }





Output Result:




Quantity: 4
Li Ming
Liu Fang
zhang ming
ZHANG SAN





2. General situation
Requirements: Fuzzy query According to name, address, memo, ignoring case, address requirements start matching.
Description: This is a common case, mainly demonstrating changing the default string matching method, changing the default case ignore mode, property-specific query mode configuration, ignoring the property list configuration.




// Create query condition data object
        Customer customer = new Customer ();
        customer.setName ("zhang");
        customer.setAddress ("Henan Province");
        customer.setRemark ("BB");

        // Create a matcher, that is, how to use query conditions
        ExampleMatcher matcher = ExampleMatcher.matching () // Build the object
                .withStringMatcher (StringMatcher.CONTAINING) // Change the default string matching method: fuzzy query
                .withIgnoreCase (true) // Change the default case ignore method: ignore case
                .withMatcher ("address", GenericPropertyMatchers.startsWith ()) // Addresses are queried using "start matching"
                .withIgnorePaths ("focus"); // Ignore attributes: whether to follow. Because it is a basic type, it needs to be ignored
        
        // Create an instance
        Example <Customer> ex = Example.of (customer, matcher);
        
        //Inquire
        List <Customer> ls = dao.findAll (ex);
        
        // output result
        System.out.println ("Amount:" + ls.size ());
        for (Customer bo: ls)
        {
            System.out.println (bo.getName ());
        }





Output Result:




Quantity: 2
zhang ming
ZHANG SAN





3, multi-level query
Requirements: Query all potential customers
Description: Main demo multi-level attribute query




// Create query condition data object
         CustomerType type = new CustomerType ();
         type.setCode ("01"); // Number 01 represents a potential customer
         Customer customer = new Customer ();
         customer.setCustomerType (type);

         // Create a matcher, that is, how to use query conditions
         ExampleMatcher matcher = ExampleMatcher.matching () // Build the object
                 .withIgnorePaths ("focus"); // Ignore attributes: whether to follow. Because it is a basic type, it needs to be ignored
        
         // Create an instance
         Example <Customer> ex = Example.of (customer, matcher);
        
         //Inquire
         List <Customer> ls = dao.findAll (ex);
        
         // output result
         System.out.println ("Amount:" + ls.size ());
         for (Customer bo: ls)
         {
             System.out.println (bo.getName ());
         }





Output Result:




Quantity: 4
Li Ming
Li Li
Zhang Qiang
ZHANG SAN





4. Query null value
Requirement: Customer with address is null
Description: The main demo changes the "Null value handling Method"




// Create query condition data object
         Customer customer = new Customer ();

         // Create a matcher, that is, how to use query conditions
         ExampleMatcher matcher = ExampleMatcher.matching () // Build the object
                 .withIncludeNullValues () // Change the "null value processing method": include
                 .withIgnorePaths ("id", "name", "sex", "age", "focus", "addTime", "remark", "customerType"); // Ignore other properties
        
         // Create an instance
         Example <Customer> ex = Example.of (customer, matcher);
        
         //Inquire
         List <Customer> ls = dao.findAll (ex);
        
         // output result
         System.out.println ("Amount:" + ls.size ());
         for (Customer bo: ls)
         {
             System.out.println (bo.getName ());
         } 





Spring Data JPA Instance Query


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.