Use Spring Mongodb access method Daquan --Spring Data MongoDB

1 Overview

Spring Data MongoDB is the Spring framework to access mongodb artifact, it can be very convenient means of reading and writing mongo database. This article describes the use of Spring Data MongoDB are several ways to access the database mongodb:

  • Use Query and Criteria class
  • JPA query method automatically generated
  • Use @Query comment JSON-based query

Before you begin, you first need to rely on the introduction of maven

1.1 add Maven dependencies

If you want to use Spring Data MongoDB, you need to add the following entry to your pom.xml file:

<dependency>
    <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.9.6.RELEASE</version> </dependency>

According to the version selected.

2. Archie

Spring Data used to query one of the most common method is to use the Query and MongoDB Criteria class, they are very close to the local operator.

2.1 is query

In the following example - we are looking for a user named Eric.

We take a look at our database:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 55 } }]

Let's look at the code query:

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Eric"));
List<User> users = mongoTemplate.find(query, User.class);

As expected, this logic is returned:

{
    "_id" : ObjectId("55c0e5e5511f0a164a581907"),
    "_class" : "org.baeldung.model.User",
    "name" : "Eric", "age" : 45 }

2.2 Regular query

Regular expressions are a more flexible and powerful query types. This uses a standard use MongoDB $ regex, and returns the standard is applicable to all the records of this field regular expression.

Its role is similar to startingWith, endingWith operation - let's look at an example.

Looking at all the user name beginning with A, which is the state of the database:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 } ]

Let's create a query:

Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query,User.class);

This running and return two records:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581908"),
        "_class" : "org.baeldung.model.User",
        "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 } ]

Here is another simple example, to find the names of all users at the end of c:

Query query = new Query();
query.addCriteria(Criteria.where("name").regex("c$"));
List<User> users = mongoTemplate.find(query, User.class);

So the result is:

{
    "_id" : ObjectId("55c0e5e5511f0a164a581907"),
    "_class" : "org.baeldung.model.User",
    "name" : "Eric", "age" : 45 }

2.3 LT and GT

$ Lt (less than) and $ gt operators (greater than).

Let's take a quick look at an example - we are looking for all users between the ages of 20 and 50 years old.

The database is:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 55 } }

Construct a query:

Query query = new Query();
query.addCriteria(Criteria.where("age").lt(50).gt(20)); List<User> users = mongoTemplate.find(query,User.class);

Results - older than 20 and less than 50 for all users:

{
    "_id" : ObjectId("55c0e5e5511f0a164a581907"),
    "_class" : "org.baeldung.model.User",
    "name" : "Eric", "age" : 45 }

2.4 Sort Results

Sort specify the sort order for the results.

First of all - there is existing data:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 } ]

After performing the sort:

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "age"));
List<User> users = mongoTemplate.find(query,User.class);

This is the result of the query - well sort by age:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581908"),
        "_class" : "org.baeldung.model.User",
        "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 }, { "_id" : ObjectId("55c0e5e5511f0a164a581907"), "_class" : "org.baeldung.model.User", "name" : "Eric", "age" : 45 } ]

2.5 Paging

Let's look at a simple example of the use of paging.

This is the state of the database:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 } ]

Now, the query logic, only one page size is 2:

final Pageable pageableRequest = new PageRequest(0, 2);
Query query = new Query(); query.with(pageableRequest);

result:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581907"),
        "_class" : "org.baeldung.model.User",
        "name" : "Eric", "age" : 45 }, { "_id" : ObjectId("55c0e5e5511f0a164a581908"), "_class" : "org.baeldung.model.User", "name" : "Antony", "age" : 33 } ]

To explore the full details of this API, here is a document Query and Criteria class.

3. The method of generating a query (Generated Query Methods)

Generating a query method is a feature of the JPA, it can also be used in the Spring Data Mongodb years.

To do 2 in function, only need to declare interface methods can be,

public interface UserRepository 
  extends MongoRepository<User, String>, QueryDslPredicateExecutor<User> { ... }

3.1 FindByX

We will simply begin by exploring findBy types of queries - in this case, by using this name:

List<User> findByName(String name);

And on an identical 2.1 - query will have the same result, to find all users with the given name:

List<User> users = userRepository.findByName("Eric");

3.2 StartingWith and endingWith.

Here is a simple example of a process operation of:

List<User> findByNameStartingWith(String regexp);

List<User> findByNameEndingWith(String regexp);

Of course, the actual use of this very simple example:

List<User> users = userRepository.findByNameStartingWith("A");
List<User> users = userRepository.findByNameEndingWith("c");

The result is exactly the same.

3.3 Between

Similar to the 2.3, which returns all users between the ages ageGT and ageLT of:

List<User> findByAgeBetween(int ageGT, int ageLT);
List<User> users = userRepository.findByAgeBetween(20, 50);

3.4 Like和OrderBy

Let's look at this more advanced example - to generate queries combination of both types of modifiers.

We are going to find all users whose name contains the letter A, and we will arrange the order of the results Age:

List<User> users = userRepository.findByNameLikeOrderByAgeAsc("A");

result:

[
    {
        "_id" : ObjectId("55c0e5e5511f0a164a581908"),
        "_class" : "org.baeldung.model.User",
        "name" : "Antony", "age" : 33 }, { "_id" : ObjectId("55c0e5e5511f0a164a581909"), "_class" : "org.baeldung.model.User", "name" : "Alice", "age" : 35 } ]

4. JSON query methods

If we are unable to represent the query method name or condition, then we can do something lower level - use @Query comment.

Through this comment, we can specify a primitive query - Mongo JSON as a query string.

4.1 FindBy

Let's start with a simple and see how we will be the first by finding a method of the type:

@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);

This method should return the user by name - placeholder 0 refers to the first argument of the method?.

4.2 $regex

Let's look at a regular expression driven inquiry - which of course will produce the same result with 2.2 and 3.2:

@Query("{ 'name' : { $regex: ?0 } }")
List<User> findUsersByRegexpName(String regexp);

Usage is exactly the same:

List<User> users = userRepository.findUsersByRegexpName("^A");
List<User> users = userRepository.findUsersByRegexpName("c$");

4.3. $ Lt gt $ and

Now we realize lt and gt query:

@Query("{ 'age' : { $gt: ?0, $lt: ?1 } }")
List<User> findUsersByAgeBetween(int ageGT, int ageLT);

5 Conclusion

In this article, we discuss the common methods using Spring Data MongoDB's query.

Exemplified herein can be from the  spring-data-mongodb download here.

This article reference A Guide to Queries in Spring Data MongoDB


Author: Jadepeng
Source: jqpeng technical notepad - http://www.cnblogs.com/xiaoqi
Your support is the greatest encouragement blogger, thank you for your read.
This article belongs to the author of all, welcome to reprint, but without the author's consent declared by this section must be retained, and given the original connection in the apparent position of the article page, otherwise the right to pursue legal responsibilities.

Guess you like

Origin www.cnblogs.com/morganlin/p/12014216.html