SpringBoot 2 整合MongoDB,做个简单的增删改查

不管用的是什么数据库,增删改查肯定少不了。现在就用SpringBoot整合MongoDB来做一套增删改查练练手。

环境配置:
MongoDB 4.2.2
SpringBoot 2.1.4

首先,在项目的pom文件里引入SpringBoot整合MongoDB的架包;

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

第二步,在application.properties里加入MongoDB的配置信息;

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/log_info

相较于其他数据库的配置,MongoDB的配置非常精简;

第三步,直接调用MongoTemplate实现增加改查;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entity.User;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;

/**
 * 
 * @author 程就人生
 * @date 2020年1月9日
 */
@RestController
public class MongodbController {

    @Autowired
    private MongoTemplate mongoTemplate; 
    
    @GetMapping("/add")
    public void add(){
        List<User> userList = new ArrayList<User>();
        User user;
        for(int i=0;i<100;i++){
            user = new User();
            user.setName("用户" + i);
            user.setSex((byte)(i%2==0?1:0));
            user.setBrithday(new Date());
            user.setAddress("江苏省 苏州市");
            userList.add(user);
        }
        //批量添加,单个对象用insert
        userList = (List<User>) mongoTemplate.insertAll(userList);
        System.out.println("新增影响行数:" + userList.size());
    }
    
    /**
     * 修改语句
     * @param id
     * @param name
     *
     */
    @GetMapping("/update")
    public void update(String id, String name){
        //修改条件
        Query query = new Query();
        Criteria criteria = new Criteria();
        //此处必须用and,用where时实现
        criteria.and("_id").is(id);
        query.addCriteria(criteria);
        Update update = new Update();
        update.set("name", name);
        //updateFirst总是修改第一条
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, User.class);
        System.out.println("修改影响行数:" + updateResult.getModifiedCount());
    }
    
    /**
     * 删除语句
     * @param id
     *
     */
    @GetMapping("/remove")
    public void remove(String id){
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("_id").is(id);
        query.addCriteria(criteria);
        DeleteResult deleteResult = mongoTemplate.remove(query,User.class);
        System.out.println("删除影响行数:" + deleteResult.getDeletedCount());
    }
    
    /**
     * 查询列表
     * @return
     *
     */
    @GetMapping("/list")
    public List<User> list(String name, Byte sex, String brithday){     
        Query query = new Query();
        //查询条件设置
        Criteria criteria = new Criteria();
        //查询条件设置        
        Pattern pattern = null;
        if(!StringUtils.isEmpty(name)){
            //用正则匹配进行模糊查询,完全匹配 :"^王$",右匹配: "^.*王$",左匹配:"^王.*$",模糊匹配:"^.*王.*$"
            pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            criteria.and("name").regex(pattern);
        }
        if(sex != null){
            //is完全匹配
            criteria.and("sex").is(sex);
        }
        //操作时间
        if(!StringUtils.isEmpty(brithday)){
            //日期的比较
            Date startDate = fromStringToDate("yyyy-MM-dd", brithday);
            //大于等于,大于用gt,小于等于用lte,小于用lt
            criteria.and("brithday").gte(startDate);
        }       
        query.addCriteria(criteria);
        //获取信息总条数
        Long count = mongoTemplate.count(query, User.class);
        System.out.println("数据总共:" + count + "条");
        //查询10条
        query.limit(10);
        //跳过前10数据,用于分页查询
        //query.skip(10);
        //设置排序
        Sort sort = new Sort(Sort.Direction.DESC, "brithday");
        query.with(sort);
        return mongoTemplate.find(query, User.class);
    }
    
    
    /**
     * 将string转换成Date格式
     * @param formatStr
     * @param strDate
     * @return
     */
    public static Date fromStringToDate(String formatStr, String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }
}

最后,测试
新增测试,这里采用批量新增,在浏览器地址栏输入http://localhost:8080/add,然后在MongoDB客户端查看运行结果;

新增结果图

修改测试,拷贝第二个的id,将其name修改掉,浏览器地址栏输入:

http://localhost:8080/update?id=5e1723f0555bbb34ec9e779e&name=的点点滴滴
修改测试结果图

删除测试,拷贝第三个的id,在浏览器地址栏输入:

http://localhost:8080/remove?id=5e1723f0555bbb34ec9e779f
删除测试结果

查询测试,查询name中包含19的数据,并查看结果:


查询测试

还有其他的两个查询条件,不妨试一试,看看效果如何。

MongoDB的配置文件为何如此简单呢?那些默认的参数又在哪里?

spring-boot-starter-data-mongodb架包自动封装了配置参数,不配置参数时,采用默认值,这些都可以通过MongoProperties类来查看,如果要扩展多数据源,则可以通过覆盖MongoProperties属性文件来实现。

package org.springframework.boot.autoconfigure.mongo;
import com.mongodb.MongoClientURI;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 默认是通过spring.data.mongodb这个前缀来获取配置文件的
*/
@ConfigurationProperties(prefix = "spring.data.mongodb")
public class MongoProperties {

    /**
     * Default port used when the configured port is {@code null}.
     */
    public static final int DEFAULT_PORT = 27017;//默认端口号

    /**
     * Default URI used when the configured URI is {@code null}.
     */
    public static final String DEFAULT_URI = "mongodb://localhost/test";//默认test数据库

    /**
     * Mongo server host. Cannot be set with URI.
     */
    private String host;

    /**
     * Mongo server port. Cannot be set with URI.
     */
    private Integer port = null;

    /**
     * Mongo database URI. Cannot be set with host, port and credentials.
     */
    private String uri;

    /**
     * Database name.
     */
    private String database;

    /**
     * Authentication database name.
     */
    private String authenticationDatabase;

    /**
     * GridFS database name.
     */
    private String gridFsDatabase;

    /**
     * Login user of the mongo server. Cannot be set with URI.
     */
    private String username;

    /**
     * Login password of the mongo server. Cannot be set with URI.
     */
    private char[] password;

    /**
     * Fully qualified name of the FieldNamingStrategy to use.
     */
    private Class<?> fieldNamingStrategy;

    public String getHost() {
        return this.host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getDatabase() {
        return this.database;
    }

    public void setDatabase(String database) {
        this.database = database;
    }

    public String getAuthenticationDatabase() {
        return this.authenticationDatabase;
    }

    public void setAuthenticationDatabase(String authenticationDatabase) {
        this.authenticationDatabase = authenticationDatabase;
    }

    public String getUsername() {
        return this.username;
    }

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

    public char[] getPassword() {
        return this.password;
    }

    public void setPassword(char[] password) {
        this.password = password;
    }

    public Class<?> getFieldNamingStrategy() {
        return this.fieldNamingStrategy;
    }

    public void setFieldNamingStrategy(Class<?> fieldNamingStrategy) {
        this.fieldNamingStrategy = fieldNamingStrategy;
    }

    public String getUri() {
        return this.uri;
    }

    public String determineUri() {
        return (this.uri != null) ? this.uri : DEFAULT_URI;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public Integer getPort() {
        return this.port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public String getGridFsDatabase() {
        return this.gridFsDatabase;
    }

    public void setGridFsDatabase(String gridFsDatabase) {
        this.gridFsDatabase = gridFsDatabase;
    }

    public String getMongoClientDatabase() {
        if (this.database != null) {
            return this.database;
        }
        return new MongoClientURI(determineUri()).getDatabase();
    }

}