spring-boot整合mongodb的案例
阅读原文时间:2023年07月11日阅读:1

1.简介

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

2.运行环境

开发工具:intellij idea

JDK版本:1.8

项目管理工具:Maven 4.0.0

3.Maven Plugin管理


http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0

 <groupId>com.goku</groupId>  
 <artifactId>spring-boot-mongodb</artifactId>  
 <version>1.0-SNAPSHOT</version>

 <parent>  
     <groupId>org.springframework.boot</groupId>  
     <artifactId>spring-boot-starter-parent</artifactId>  
     <version>1.5.6.RELEASE</version>  
 </parent>

 <dependencies>  
     <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>  
     <dependency>  
         <groupId>org.springframework.boot</groupId>  
         <artifactId>spring-boot-devtools</artifactId>  
         <optional>true</optional>  
     </dependency>  
     <dependency>  
         <groupId>org.springframework.boot</groupId>  
         <artifactId>spring-boot-starter-data-mongodb</artifactId>  
     </dependency>  
 </dependencies>

 <build>  
     <plugins>  
         <plugin>  
             <groupId>org.springframework.boot</groupId>  
             <artifactId>spring-boot-maven-plugin</artifactId>  
             <configuration>  
                 <fork>true</fork>  
             </configuration>  
         </plugin>  
     </plugins>  
 </build>

4.application.properties编写

spring.data.mongodb.uri= mongodb://localhost:27017/goku_db1

5.DemoApplication启动类编写

package com.goku.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

/**
* Created by nbfujx on 2017/11/20.
*/
// Spring Boot 应用的标识
@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

 public static void main(String\[\] args) {  
     // 程序启动入口  
     // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件  
     SpringApplication.run(DemoApplication.class,args);  
 }  

}

6.User编写

package com.goku.demo.model;

import org.springframework.data.annotation.Id;

import java.io.Serializable;

/**
* Created by nbfujx on 2017-12-07.
*/
public class User implements Serializable {

private static final long serialVersionUID = -1L;

@Id  
private Long id;  
private String username;  
private Integer age;

public User(Long id, String username, Integer age) {  
    this.id = id;  
    this.username = username;  
    this.age = age;  
}

public Long getId() {  
    return id;  
}

public void setId(Long id) {  
    this.id = id;  
}

public String getUsername() {  
    return username;  
}

public void setUsername(String username) {  
    this.username = username;  
}

public Integer getAge() {  
    return age;  
}

public void setAge(Integer age) {  
    this.age = age;  
}

@Override  
public String toString()  
{  
    return "\\"User:{\\"id\\":\\""+id+"\\",\\"username\\":\\""+username+"\\",\\"age\\":\\""+age+"\\"}\\"";  
}  

}

7.UserRepository编写

与HibernateRepository类似,通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查,要使用Repository的功能,先继承MongoRepository接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。

但是MongoRepository实现了的只是最基本的增删改查的功能,要想增加额外的查询方法,可以按照以下规则定义接口的方法。自定义查询方法,格式为“findBy+字段名+方法后缀”,方法传进的参数即字段的值,此外还支持分页查询,通过传进一个Pageable对象,返回Page集合。

下面是支持的查询类型,每三条数据分别对应:(方法后缀,方法例子,mongodb原生查询语句)

package com.goku.demo.repository;

import com.goku.demo.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

import java.util.List;

/**
* Created by nbfujx on 2017-12-08.
*/
public interface UserRepository extends MongoRepository {

 /\*\*  
  \* Like(模糊查询)  
  \* {"username" : name} ( name as regex)  
  \* \*/  
 List<User> findByUsernameLike(String username);

 /\*\*  
  \* Like(模糊查询)  
  \* {"username" : name}  
  \* \*/  
 List<User> findByUsername(String username);

 /\*\*  
  \* GreaterThan(大于)  
  \* {"age" : {"$gt" : age}}  
  \* \*/  
 List<User> findByAgeGreaterThan(int age);  
 /\*\*  
  \* LessThan(小于)  
  \* {"age" : {"$lt" : age}}  
  \* \*/  
 List<User> findByAgeLessThan(int age);  
 /\*\*  
  \* Between(在...之间)  
  \* {{"age" : {"$gt" : from, "$lt" : to}}  
  \* \*/  
 List<User> findByAgeBetween(int from, int to);

 /\*\*  
  \* IsNotNull, NotNull(是否非空)  
  \*  {"username" : {"$ne" : null}}  
  \* \*/  
 List<User> findByUsernameNotNull();

 /\*\*  
  \* IsNull, Null(是否为空)  
  \*   {"username" : null}  
  \* \*/  
 List<User> findByUsernameNull();

 /\*\*  
  \* Not(不包含)  
  \*    {"username" : {"$ne" : name}}  
  \* \*/  
 List<User> findByUsernameNot(String name);

 /\*\*  
  \*  Near(查询地理位置相近的)  
  \*  {"location" : {"$near" : \[x,y\]}}  
  \* \*/  
  // findByLocationNear(Point point)

 /\*\*  
  \* Within(在地理位置范围内的)  
  \*   {"location" : {"$within" : {"$center" : \[ \[x, y\], distance\]}}}  
  \* \*/  
 //findByLocationWithin(Circle circle)

 /\*\*  
  \*   Within(在地理位置范围内的)  
  \*     {"location" : {"$within" : {"$box" : \[ \[x1, y1\], x2, y2\]}}}  
  \* \*/  
// findByLocationWithin(Box box)

}

尽管以上查询功能已经很丰富,但如果还不能满足使用情况的话可以用一下方法---基于mongodb原本查询语句的查询方式。

 @Query("{\\"username\\":{\\"$regex\\":?0}, \\"age\\": ?1}")  
 Page<User> findByNameAndAgeRange(String name,int age,Pageable page);

 @Query(value="{\\"username\\":{\\"$regex\\":?0},\\"age\\":{\\"$gte\\":?1,\\"$lte\\": ?2}}")  
 Page<User> findByNameAndAgeRange2(String name,int ageFrom,int ageTo,Pageable page);

 @Query(value="{\\"username\\":{\\"$regex\\":?0},\\"age\\":{\\"$gte\\":?1,\\"$lte\\": ?2}}",fields="{\\"username\\" : 1, \\"age\\" : 1}")  
 Page<User> findByNameAndAgeRange3(String name,int ageFrom,int ageTo,Pageable page);

8.UserRepositoryTest测试编写

package test.com.goku.repository;

import com.goku.demo.DemoApplication;
import com.goku.demo.model.User;
import com.goku.demo.repository.UserRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
* Created by nbfujx on 2017-12-08.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class UserRepositoryTest {

 private final Logger logger = LoggerFactory.getLogger(getClass());

 @Autowired  
 private UserRepository userRepository;

 @Before  
 public void setUp() {  
     //userRepository.deleteAll();  
 }

 @Test  
 public void test() throws Exception {

     // 创建10个User,并验证User总数  
     userRepository.save(new User(1L, "didi", 30));  
     userRepository.save(new User(2L, "mama", 40));  
     userRepository.save(new User(3L, "kaka", 50));  
     userRepository.save(new User(4L, "didi2", 30));  
     userRepository.save(new User(5L, "mama", 40));  
     userRepository.save(new User(6L, "kaka2", 50));  
     userRepository.save(new User(7L, "kaka", 50));  
     userRepository.save(new User(8L, "kao", 50));  
     userRepository.save(new User(9L, "ekakae", 50));  
     userRepository.save(new User(10L, "kaka5", 50));  
     userRepository.save(new User(11L, "", 50));  
     userRepository.save(new User(12L, null, 50));  
     this.logger.info(String.valueOf(userRepository.findAll().size()));

     // 删除一个User,再验证User总数  
     /\*User u = userRepository.findOne(1L);  
     this.logger.info(u.toString());  
     userRepository.delete(u);  
     this.logger.info(String.valueOf(userRepository.findAll().size()));

     // 删除一个User,再验证User总数  
     u = userRepository.findByUsername("mama").get(0);  
     this.logger.info(u.toString());  
     userRepository.delete(u);  
     this.logger.info(String.valueOf(userRepository.findAll().size()));\*/

 }

 @Test  
 public void test2() throws Exception {

     // 删除一个User,再验证User总数  
     List<User> u1 = userRepository.findByUsernameLike("kaka");  
     this.logger.info(u1.toString());  
     List<User> u2 = userRepository.findByUsername("mama");  
     this.logger.info(u2.toString());  
     List<User> u3 = userRepository.findByAgeGreaterThan(40);  
     this.logger.info(u3.toString());  
     List<User> u4 = userRepository.findByAgeLessThan(40);  
     this.logger.info(u4.toString());  
     List<User> u5 = userRepository.findByAgeBetween(30,45);  
     this.logger.info(u5.toString());  
     List<User> u6 = userRepository.findByUsernameNotNull();  
     this.logger.info(u6.toString());  
     List<User> u7 = userRepository.findByUsernameNull();  
     this.logger.info(u7.toString());  
     List<User> u8 = userRepository.findByUsernameNot("kaka");  
     this.logger.info(u8.toString());

 }

 @Test  
 public void test3() throws Exception {

     Pageable pageable = new PageRequest(0,10);  
     Page<User> u1 = userRepository.findByNameAndAgeRange("kaka",50,pageable);  
     this.logger.info(u1.toString());  
     Page<User> u2 = userRepository.findByNameAndAgeRange2("kaka",0,50,pageable);  
     this.logger.info(u2.toString());  
     Page<User> u3 = userRepository.findByNameAndAgeRange3("kaka",0,50,pageable);  
     this.logger.info(u3.toString());

 }  

}

9.GITHUB地址

https://github.com/nbfujx/springBoot-learn-demo/tree/master/spring-boot-mongodb