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

Spring Data JPA instance query

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

Third, understand the "case query"

1. Concept definition:

In the above example, the "instance" is created like this: Example ex = Example.of (customer, matcher); as we can see, the Example object is jointly created by customer and matcher. For ease of explanation, let's first clarify some definitions.

Entity object: the domain object corresponding to Table in the persistence framework. An object represents a record in the database table, such as the Customer object in the example above. When building a query condition, an entity object represents the "numeric" part of the query condition. For example, to query a customer surnamed "Liu", the entity object can only store the conditional value "Liu".

B, matcher: ExampleMatcher object, which matches the "entity object", indicates how to use the "value" in the "entity object" to query, it represents the "query method" and explains how to look it up. For example, to query a customer surnamed "Liu", that is, a customer whose first name begins with "Liu", the object represents the query method of "starting with so-and-so", as in the above example: withMatcher ("name", GenericPropertyMatchers.startsWith ())

C, instance: that is, the Example object, which represents the complete query condition. Created by entity objects (query condition values) and matchers (query methods).

To understand the "instance query", as the name implies, is to query through an example. The Customer object is to be queried, and the query condition is also a Customer object, using an existing customer object as an example to query the object that matches this example.

2. Characteristics and constraints:

1. Dynamic query is supported. That is, if the number of query conditions is not fixed, for example, if there are multiple filtering conditions in the customer list, if the user enters a value in the "address" query box, it needs to be filtered by address. If no value is entered, ignore this filtering condition. The corresponding implementation is to set the address attribute value to the specific condition value or to null when building the query condition Customer object.

2. Filter condition grouping is not supported. That is, filter conditions are not supported to be connected with or (or), and all filter lookups are simply connected with and (and).

3. Only the start / include / end / regular expression matching of the string and the exact matching of other attribute types are supported. When querying, you can only pass in a filter condition value for an attribute to be matched (such as: name name). For example, if you want to query a customer surnamed "Liu", the condition value of "Liu" is stored in the name attribute of the Customer object that represents the condition object. For the filtering of "name", there is only one location where the filter value is stored, and there is no way to pass in two filter values at the same time. It is precisely because of this limitation that some queries cannot be supported. For example, if you want to query customers added within a certain period of time, the corresponding attribute is addTime, and you need to pass in two conditional values, "start time" and "end time". However, this query method does not have the location to store two values, so it is impossible to complete such a query.

Fourth, focus on understanding ExampleMatcher

1. Factors to be considered

The expression of the query condition has two parts, one is the condition value, the other is the query mode. Condition values are stored in entity objects (such as Customer objects), which is relatively simple. When a filter condition value is passed into a page, it is stored in the corresponding attribute, and when it is not passed in, the attribute remains at its default value. The query method is represented by the matcher ExampleMatcher. The situation is relatively complicated, and the factors to be considered are:

(1) the treatment of Null value. When a condition value is Null, should this filter condition be ignored, or should it match the records in the database table where the field value is Null?

(2) basic types of processing. For example, the age age in the customer Customer object is int, and when the page does not pass a conditional value, it defaults to 0 and has a value, so do you participate in the query?

(3) ignore some attribute values. An entity object has many attributes. Does each attribute participate in the filtering? Can some attributes be ignored?

(4) different filtering methods. Also as a string value, it is possible that the "name" wants an exact match and the "address" wants a fuzzy match. How to do that?

(5) match case. When matching strings, sometimes you want to ignore case, and sometimes you don't. How do you do that?

2. Five configuration items

Around the above series of situations, five configurations are defined in ExampleMatcher to solve these problems.

Public class ExampleMatcher {NullHandler nullHandler; / / Null value handling method StringMatcher defaultStringMatcher; / / default string matching method boolean defaultIgnoreCase; / / default case ignore method PropertySpecifiers propertySpecifiers; / / each attribute specific query method Set ignoredPaths; / / ignore attribute list.}

(1) nullHandler:Null value handling, enumeration type, there are 2 optional values, INCLUDE (including), IGNORE (ignore). Identifies whether an attribute value (condition value) in an entity object as a condition is Null and whether it participates in filtering. When the option value is INCLUDE, it still participates in the filtering and matches the record in the database table in which the field value is Null; if the value is IGNOREE, it does not participate in the filtering.

(2) defaultStringMatcher: default string matching method, enumerated type, there are 6 optional values, DEFAULT (default, effect is the same as EXACT), EXACT (equal), STARTING (start matching), ENDING (end matching), CONTAINING (include, fuzzy matching), REGEX (regular expression). This configuration is valid for all string attribute filtering unless the attribute defines its own matching method separately in propertySpecifiers.

(3) defaultIgnoreCase: the default case ignore method is Boolean. When the value is false, it is not ignored, and the size is not equal. This configuration is valid for all string property filtering, unless the property separately defines its own case-ignoring method in propertySpecifiers.

(4) propertySpecifiers: each attribute-specific query mode, which describes the query mode defined separately by each attribute. Each query method contains four elements: attribute name, string matching mode, case ignore mode, attribute converter. If the attribute does not define the query method separately, or if an element is not defined in the separate query method (for example, string matching method), the default value defined in ExampleMatcher, that is, the values of defaultStringMatcher and defaultIgnoreCase described above, is adopted.

(5) ignoredPaths: ignore the attribute list, and ignored attributes do not participate in query filtering.

3. Operation method

A series of ways are defined in ExampleMatcher to set these five settings, all of which return an ExampleMatcher object, so chain programming configuration is supported.

(1) create a default ExampleMatcher object.

Definition:

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 (equal)

C 、 defaultIgnoreCase:false . Default case ignore method: do not ignore

D, propertySpecifiers: empty. Each attribute is specific to the query mode, empty.

E, ignoredPaths: empty list. Ignore attribute list, empty list.

(2) change the way of dealing with null values.

Definition:

Public ExampleMatcher withNullHandler (NullHandler nullHandler)

Public ExampleMatcher withIncludeNullValues ()

Public ExampleMatcher withIgnoreNullValues ()

To have an effect:

Change the configuration item nullHandler, set to: specified value, INCLUDE (including), IGNORE (ignore).

(3) change the default string matching mode.

Definition:

Public ExampleMatcher withStringMatcher (StringMatcher defaultStringMatcher)

To have an effect:

Change the configuration item defaultStringMatcher to the specified value.

(4) change the default case ignore mode.

Definition:

Public ExampleMatcher withIgnoreCase ()

Public ExampleMatcher withIgnoreCase (boolean defaultIgnoreCase)

To have an effect:

Change the configuration item defaultIgnoreCase, set to: true, and specify the value.

(5) add attributes to the ignore attribute list.

Definition:

Public ExampleMatcher withIgnorePaths (String... IgnoredPaths)

To have an effect:

Change the configuration item ignoredPaths to add one or more attributes to the list.

(6) configure attribute-specific query method

The specific query mode of an attribute contains three pieces of information: string matching mode, case ignore mode, attribute converter, which is stored in propertySpecifiers, and the GenericPropertyMatcher class is used to transmit configuration information during operation. There are four ways to change the configuration. When these four methods operate, they all use the method of incremental change, that is, if no "specific query method" is defined for the attribute, one will be defined and configured according to the "non-empty information" passed in. If it has been defined, it will be updated according to the "non-empty information" passed in. If string matching and case ignorance are not set in a specific query method, the default configuration in ExampleMatcher is used for the query.

A, the way to customize the class.

Definition:

Public ExampleMatcher withMatcher (String propertyPath, MatcherConfigurer matcherConfigurer)

To have an effect:

Add or update the configuration of the property "specific query method" to the propertySpecifiers.

Parameter description:

PropertyPath: the property name of the specific query to be configured.

MatcherConfigurer: custom class object. The custom class needs to implement the MatcherConfigurer interface and specify the relevant configuration in the interface's configureMatcher () implementation method.

B, directly pass into the general attribute query object mode.

Definition:

Public ExampleMatcher withMatcher (String propertyPath, GenericPropertyMatcher genericPropertyMatcher)

To have an effect:

Add or update the configuration of the property "specific query method" to the propertySpecifiers.

Parameter description:

PropertyPath: the property name of the specific query to be configured.

GenericPropertyMatcher: pass in a generic query object directly. Static methods for creating common objects are provided in the ExampleMatcher.GenericPropertyMatchers utility class, and all methods return GenericPropertyMatcher objects, so chained programming configuration is supported.

In addition: the GenericPropertyMatcher class itself provides a number of methods for changing related configuration items.

C. the case-ignoring mode of the change

Definition:

Public ExampleMatcher withIgnoreCase (String... PropertyPaths)

To have an effect:

Add or update the case ignore configuration in the property "specific query mode" to the propertySpecifiers.

D, set property converter

Definition:

Public ExampleMatcher withTransformer (String propertyPath, PropertyValueTransformer propertyValueTransformer)

To have an effect:

Add or update the property Converter configuration in the property "specific query method" to the propertySpecifiers.

5. Description of common situations

1. About basic data types.

In entity objects, avoid using basic data types and use wrapper types. If the basic type has been adopted

If this property is queried without filtering, it is added to the ignore list (ignoredPaths).

2. How to deal with null value.

The default value is IGNORE (ignore), that is, when the condition value is null, the filter condition is ignored, and the general business can be satisfied in this way. When you need to query records in a database table whose attribute is null, you can set the value to INCLUDE. In this case, attributes that do not need to participate in the query must be added to the ignore list (ignoredPaths), otherwise the data will not be found.

3. Default configuration and special configuration.

When creating a matcher by default, the string uses exact matching and does not ignore case. You can change this default matching through operational methods to meet the needs of most query conditions, such as changing the "string matching method" to CONTAINING (inclusive, fuzzy matching), which is a more common case. For individual attributes that require specific query methods, you can configure "attribute-specific query methods" to meet the requirements.

4. Non-string attribute

As mentioned in the constraint, non-string attributes are matched exactly, that is, equal to.

5. Ignore the case problem.

Whether the size is effective or not depends on the database. For example, in the MySql database, when the table structure is created by default, the case of the field is ignored, so whether this is configured or not is ignored. If the business needs to be strictly case-sensitive, you can change the database table structure attributes to achieve, specific Baidu.

VI. Examples of common queries

Take the entity objects and simulation data in "getting started" as an example, list some common queries for easy reference when developing.

1. The absence of a matcher

Requirements: the inquiry address is "Zhengzhou City, Henan Province", and focus on the customers.

Note: when the default matcher meets the conditions, there is no need to create a matcher.

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

Output result:

Quantity: 4 Li Ming Liu Fang zhang mingZHANG SAN

2. General situation

Requirements: according to the name, address, remarks for fuzzy query, ignore case, address requirements start to match.

Description: this is a general situation, mainly demonstrates changing the default string matching mode, changing the default case ignore mode, attribute-specific query mode configuration, ignoring attribute list configuration.

/ / create query condition data object Customer customer = new Customer (); customer.setName ("zhang"); customer.setAddress ("Henan"); customer.setRemark ("BB") / / create a matcher That is, how to use the query condition ExampleMatcher matcher = ExampleMatcher.matching () / / to build an object. WithStringMatcher (StringMatcher.CONTAINING) / / change the default string matching method: fuzzy query .withIgnoreCase (true) / / change the default case ignore mode: ignore case .withMatcher ("address") GenericPropertyMatchers.startsWith () / / address is queried by "start matching" .withIgnorePaths ("focus") / / ignore attribute: whether to care or not. Because it is a basic type, you need to ignore / / create an instance Example ex = Example.of (customer, matcher); / / query List ls = dao.findAll (ex); / / output the result System.out.println ("quantity:" + ls.size ()) For (Customer bo:ls) {System.out.println (bo.getName ());}

Output result:

Quantity: 2zhang mingZHANG SAN

3. Multi-level query

Requirement: inquire all potential customers

Description: mainly demonstrates multi-level attribute query

/ / create the query condition data object CustomerType type = new CustomerType (); type.setCode ("01"); / / 01 represents the prospect Customer customer = new Customer (); customer.setCustomerType (type) / / create a matcher, that is, how to use the query condition ExampleMatcher matcher = ExampleMatcher.matching () / / to build an object. WithIgnorePaths ("focus"); / / ignore attribute: whether to care or not. Because it is a basic type, you need to ignore / / create an instance Example ex = Example.of (customer, matcher); / / query List ls = dao.findAll (ex); / / output the result System.out.println ("quantity:" + 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 whose address is null

Description: the main demonstration is to change the "null value handling method"

/ / create query condition data object Customer customer = new Customer () / / create a matcher, that is, how to use the query condition ExampleMatcher matcher = ExampleMatcher.matching () / to build an object. WithIncludeNullValues () / / change "null value handling": include .withIgnorePaths ("id", "name", "sex", "age", "focus", "addTime", "remark", "customerType") / / ignore other attributes / / create an instance Example ex = Example.of (customer, matcher); / / query List ls = dao.findAll (ex); / / output result System.out.println ("quantity:" + ls.size ()) For (Customer bo:ls) {System.out.println (bo.getName ());}

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

Database

Wechat

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

12
Report