Use MongoDB's Spring Boot and MongoTemplate Tutorials

In this tutorial, we will build a Spring Boot application, the application demonstrates how to use MongoDB MongoTemplate API to access data in the database.

For MongoDB, we will use mlab , it provides a MongoDB database as a service platform, so you do not even have to install MongoDB database on the computer.

Configuration

To quickly set up our project, we will use a called Spring Initializr tools. Using this tool, we can quickly provide a list of the required dependencies and download the boot program:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

When creating a new project using the Spring Boot Spring Initializr, choose only two dependencies:

  • Web (Spring Boot Starter Web)
  • MongoDB (MongoDB Starter)

Maven Dependencies

When the download project Spring Initializr generated and open its pom.xml file, you should see the Add the following dependencies:

<dependencies>  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-data-mongodb</artifactId>  </dependency>  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-web</artifactId>  </dependency>  <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-test</artifactId>     <scope>test</scope>  </dependency></dependencies><build>  <plugins>     <plugin>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-maven-plugin</artifactId>     </plugin>  </plugins></build>

Project structure

Before proceeding handling code and start the project, let us introduce the completion of all the code added to the project structure the project will have:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

The code in multiple packages tissue, thus following the principle of separation of concerns, and the code held modular.

Create a database

For MongoDB, we will use mlab . You can use mLab create a free account and use MongoDB in the cloud, without the need to download and install it on your computer.

After logging in to mLab, you will see a similar dashboard:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

To create a new database MongoDB, click Create new button:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

After entering all the details, we can confirm that:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

Once this is done, we will see a connection string, as shown below:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

在开始使用此数据库之前,我们还需要创建一个用户。让我们在上图所示的“用户”标签上执行此操作:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

现在,我们已经准备好继续写些Java代码,因为我们的mLab数据库已经完全准备就绪。

应用配置

使用Spring Boot,仅使用MongoDB连接String的单个必需属性即可轻松配置我们的应用程序:

# application propertiesserver.port=8090# MongoDB propertiesspring.data.mongodb.uri=mongodb://cicoding.cn:[email protected]:29670/cicoding_db

我们只是提供了一个MongoDB连接字符串,该字符串将由Spring Boot读取,并且将使用内部API建立连接。

建立模型

我们将创建一个简单的Person实体,其中包含一些字段,我们将使用它们来演示简单的MongoDB查询:

package com.cicoding.mongotemplatedemo.model;import org.springframework.data.annotation.Id;import org.springframework.data.mongodb.core.mapping.Document;import java.util.Calendar;import java.util.Date;import java.util.List;import java.util.Locale;import static java.util.Calendar.DATE;import static java.util.Calendar.MONTH;import static java.util.Calendar.YEAR;@Document(collection = "person")public class Person {   @Id   private String personId;   private String name;   private long age;   private List<String> favoriteBooks;   private Date dateOfBirth;   public Person() {   }   public Person(String name, List<String> childrenName, Date dateOfBirth) {       this.name = name;       this.favoriteBooks = childrenName;       this.dateOfBirth = dateOfBirth;       this.age = getDiffYears(dateOfBirth, new Date());   }   // standard getters and setters   private int getDiffYears(Date first, Date last) {       Calendar a = getCalendar(first);       Calendar b = getCalendar(last);       int diff = b.get(YEAR) - a.get(YEAR);       if (a.get(MONTH) > b.get(MONTH) ||               (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {           diff--;       }       return diff;   }   private Calendar getCalendar(Date date) {       Calendar cal = Calendar.getInstance(Locale.US);       cal.setTime(date);       return cal;   }   @Override   public String toString() {       return String.format("Person{personId='%s', name='%s', age=%d, dateOfBirth=%s}\n",               personId, name, age, dateOfBirth);   }}

除了简单的字段外,我们还添加了一些帮助程序功能,可以在保存用户的出生日期时计算该用户的年龄。这使我们不必计算用户的年龄。

定义数据访问层接口

让我们定义一个数据层接口,该接口将通知我们在应用程序中将演示多少操作。这是界面:

public interface PersonDAL {   Person savePerson(Person person);   List<Person> getAllPerson();   List<Person> getAllPersonPaginated(      int pageNumber, int pageSize);   Person findOneByName(String name);   List<Person> findByName(String name);   List<Person> findByBirthDateAfter(Date date);   List<Person> findByAgeRange(int lowerBound, int upperBound);   List<Person> findByFavoriteBooks(String favoriteBook);   void updateMultiplePersonAge();   Person updateOnePerson(Person person);   void deletePerson(Person person);}

这些是相当多的操作。真正的乐趣是当我们执行这些操作时,接下来将要做的事情。

实施数据访问层

我们将使用MongoTemplate bean,它是由Spring Boot使用上面在application.properties中定义的属性初始化的。让我们看看如何定义所需的bean:

@Repositorypublic class PersonDALImpl implements PersonDAL {    private final MongoTemplate mongoTemplate;    @Autowired    public PersonDALImpl(MongoTemplate mongoTemplate) {        this.mongoTemplate = mongoTemplate;    }    ...}

我们将开始使用简单的方法来理解查询,首先是要保存并从数据库中获取所有人员:

@Overridepublic Person savePerson(Person person) {   mongoTemplate.save(person);   return person;}@Overridepublic List<Person> getAllPerson() {   return mongoTemplate.findAll(Person.class);}

MongoTemplate为我们提供了一些抽象方法,通过这些方法我们可以将对象保存到数据库中,也可以从数据库中获取所有数据。

使用分页查询

上述从数据库中获取所有人的方法的问题在于,数据库中可能有数千个对象。 我们应该始终在查询中实现分页,以便可以确保仅从数据库中提取有限的数据:

@Overridepublic List<Person> getAllPersonPaginated(int pageNumber, int pageSize) {   Query query = new Query();   query.skip(pageNumber * pageSize);   query.limit(pageSize);   return mongoTemplate.find(query, Person.class);}

这样,一次将仅从数据库中获取pageSize个对象。

通过精确值获取对象

我们也可以通过匹配数据库中的精确值来提取对象:

@Overridepublic Person findOneByName(String name) {   Query query = new Query();   query.addCriteria(Criteria.where("name").is(name));   return mongoTemplate.findOne(query, Person.class);}@Overridepublic List<Person> findByName(String name) {   Query query = new Query();   query.addCriteria(Criteria.where("name").is(name));   return mongoTemplate.find(query, Person.class);}

我们展示了两种方法。第一种方法是从数据库中获取单个对象,而第二种方法是从数据库中获取具有匹配条件的所有对象。

按范围和数据列表查找

We can also find an object with field values ​​within a specified range. Or an object date data after the specific date. Let's see how to do this, and how to construct the same query:

@Overridepublic List<Person> findByBirthDateAfter(Date date) {   Query query = new Query();   query.addCriteria(Criteria.where("dateOfBirth").gt(date));   return mongoTemplate.find(query, Person.class);}@Overridepublic List<Person> findByAgeRange(int lowerBound, int upperBound) {   Query query = new Query();   query.addCriteria(Criteria.where("age").gt(lowerBound)           .andOperator(Criteria.where("age").lt(upperBound)));   return mongoTemplate.find(query, Person.class);}@Overridepublic List<Person> findByFavoriteBooks(String favoriteBook) {   Query query = new Query();   query.addCriteria(Criteria.where("favoriteBooks").in(favoriteBook));   return mongoTemplate.find(query, Person.class);}

Update objects

We can use Update to update query data in MongoDB. We can find an object, and then update their own fields provided:

@Overridepublic void updateMultiplePersonAge() {   Query query = new Query();   Update update = new Update().inc("age", 1);   mongoTemplate.findAndModify(query, update, Person.class);;}@Overridepublic Person updateOnePerson(Person person) {   mongoTemplate.save(person);   return person;}

In the first query, the absence of any added conditions to the query, we received all the objects. Next, we provide a clause Update, where all the user's age have increased a.

Deleting objects

Delete an object with a single method call is also relevant:

@Overridepublic void deletePerson(Person person) {   mongoTemplate.remove(person);}

We can simply pass the Query object and you want to remove the person's ID.

Making the command-line runner

We will use the command line to run the program in place to run our application, the command line to run the program will provide us with the data access layer to achieve some of the above defined features. This is the command-line runner:

package com.cicoding.mongotemplatedemo;import com.cicoding.mongotemplatedemo.dal.PersonDAL;import com.cicoding.mongotemplatedemo.model.Person;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.CommandLineRunner;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import java.util.Arrays;import java.util.Date;@SpringBootApplicationpublic class MongoTemplateApp implements CommandLineRunner {  private static final Logger LOG = LoggerFactory.getLogger("cicoding");  private final PersonDAL personDAL;  @Autowired  public MongoTemplateApp(PersonDAL personDAL) {     this.personDAL = personDAL;  }  public static void main(String[] args) {     SpringApplication.run(MongoTemplateApp.class, args);  }  @Override  public void run(String... args) {     personDAL.savePerson(new Person(           "Shubham", Arrays.asList("Harry potter", "Waking Up"), new Date(769372200000L)));     personDAL.savePerson(new Person(           "Sergey", Arrays.asList("Startup Guides", "Java"), new Date(664309800000L)));     personDAL.savePerson(new Person(           "David", Arrays.asList("Harry potter", "Success"), new Date(695845800000L)));     personDAL.savePerson(new Person(           "Ivan", Arrays.asList("Secrets of Butene", "Meeting Success"), new Date(569615400000L)));     personDAL.savePerson(new Person(           "Sergey", Arrays.asList("Harry potter", "Startup Guides"), new Date(348777000000L)));     LOG.info("Getting all data from MongoDB: \n{}",           personDAL.getAllPerson());     LOG.info("Getting paginated data from MongoDB: \n{}",           personDAL.getAllPersonPaginated(0, 2));     LOG.info("Getting person By name 'Sergey': {}",           personDAL.findByName("Sergey"));     LOG.info("Getting all person By name 'Sergey': {}",           personDAL.findOneByName("Sergey"));     LOG.info("Getting people between age 22 & 26: {}",           personDAL.findByAgeRange(22, 26));  }}

We can use a simple command to run our application:

mvn spring-boot:run

After running the application, we will be able to see in the terminal a simple output:

Use MongoDB's Spring Boot and MongoTemplate Tutorials

in conclusion

If we MongoTemplate compared with the simple Spring Data JPA, it may seem complicated, but it also allows us to construct queries on how to have more control.

Spring Data JPA extract too much about what the query structure, which will be passed to the condition of detailed information inquiries. Use MongoTemplate, we will have more fine-grained control over query composition, Spring Boot provides us with easy application development.

Guess you like

Origin www.cnblogs.com/zhaokejin/p/11950509.html