Springboot 整合mongodb 操作工具类仿mybatis-plus风格

Posted 李泰山

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot 整合mongodb 操作工具类仿mybatis-plus风格相关的知识,希望对你有一定的参考价值。

以下是仿照mybatis-plus风格操作 mongodb 的增删改查的工具类以及使用示例 

pom文件引入依赖

        <!-- mongodb -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
         <version> 1.2.70</version>
    </dependency>
        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
MongoDBUtil 工具类代码


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.result.UpdateResult;
import org.springblade.core.tool.utils.SpringUtil;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.*;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class MongoDBUtil 

    private static final Query EMPTY_QUERY = new BasicQuery("");
    private static final MongoTemplate template;

    static 
        template = SpringUtil.getBean(MongoTemplate.class);
    

    private static Query idEqQuery(Serializable id) 
        Criteria criteria = Criteria.where("id").is(id);
        return Query.query(criteria);
    

    private static Query idInQuery(Collection<? extends Serializable> idList) 
        Criteria criteria = Criteria.where("id").in(idList);
        return Query.query(criteria);
    

    private static Query eqQuery(Map<String, Object> data) 
        if (CollectionUtils.isEmpty(data)) 
            return EMPTY_QUERY;
         else 
            Criteria criteria = new Criteria();
            data.forEach((k, v) -> criteria.and(k).is(v));
            return Query.query(criteria);
        
    

    private static <T> Serializable getIdValue(T entity) 
        try 
            Field field = entity.getClass().getDeclaredField("id");
            field.setAccessible(true);
            return (Serializable) field.get(entity);
         catch (NoSuchFieldException | IllegalAccessException e) 
            e.printStackTrace();
        
        return null;
    

    private static <T> Update getUpdate(T entity) 
        Field[] fields = entity.getClass().getDeclaredFields();
        for (Field field : fields) 
            field.setAccessible(true);
            try 
                System.out.println(field.getName()+" "+field.get(entity));
             catch (IllegalAccessException e) 
                e.printStackTrace();
            
        
        return null;
    

    public static <T> void save(T entity) 
        template.save(entity);
    

    public static <T> void saveBatch(Collection<T> entityList) 
        template.insertAll(entityList);
    

    public static void removeById(Serializable id, Class<?> clazz) 
        template.remove(idEqQuery(id), clazz);
    

    public static void removeByMap(Map<String, Object> columnMap, Class<?> clazz) 
        template.remove(eqQuery(columnMap), clazz);
    

    public static void removeByIds(Collection<? extends Serializable> idList, Class<?> clazz) 
        template.remove(idInQuery(idList), clazz);
    

    public static void remove(Query query, Class<?> clazz) 
        template.remove(query, clazz);
    

    public static <T> boolean updateById(T entity) 
        Assert.notNull(entity, "entity must not be null!");
        JSONObject obj = (JSONObject) JSONObject.toJSON(entity);
        DBObject update = new BasicDBObject();
        update.put("$set", obj);
        UpdateResult result = template.updateFirst(idEqQuery(getIdValue(entity)), new BasicUpdate(update.toString()), entity.getClass());
        return result.getModifiedCount() == 1L;
    

    public static <T> void updateBatchById(Collection<T> entityList) 
        entityList.forEach(e -> updateById(e));
    

    public static void update(Query query, Update update, Class<?> clazz) 
        template.updateMulti(query, update, clazz);
    

    public static <T> void saveOrUpdate(T entity) 
        Assert.notNull(entity, "entity must not be null!");
        String key = JSONObject.toJSONString(entity);
        Update inc = new Update().inc(key, 1);
        template.upsert(idEqQuery(getIdValue(entity)), inc, entity.getClass());
    

    public static <T> void saveOrUpdateBatch(Collection<T> entityList) 
        entityList.forEach(MongoDBUtil::saveOrUpdate);
    

    public static <T> T getById(Serializable id, Class<T> clazz) 
        return template.findById(id, clazz);
    

    public static <T> T getOne(Query query, Class<T> clazz) 
        return template.findOne(query, clazz);
    

    public static <T> List<T> listByIds(Collection<? extends Serializable> idList, Class<T> clazz) 
        return template.find(idInQuery(idList), clazz);
    

    public static <T> List<T> listByMap(Map<String, Object> columnMap, Class<T> clazz) 
        return template.find(eqQuery(columnMap), clazz);
    

    public static <T> List<T> list(Class<T> clazz) 
        return template.findAll(clazz);
    

    public static <T> List<T> list(Query query, Class<T> clazz) 
        return template.find(query, clazz);
    

    public static <T> long count(Class<T> clazz) 
        return template.count(EMPTY_QUERY, clazz);
    

    public static <T> long count(Query query, Class<T> clazz) 
        return template.count(query, clazz);
    

    public static <T> IPage<T> page(IPage page, Class<T> clazz) 
        page.setTotal(count(clazz));
        Pageable pageable = PageRequest.of((int) (page.getCurrent()+1), (int) page.getSize());
        List<T> records = template.find(new Query().with(new Sort(Sort.Direction.DESC, "id")).with(pageable), clazz);
        page.setPages(page.getPages());
        page.setRecords(records);
        return page;
    

    public static <T> IPage<T> page(IPage page, Query query, Class<T> clazz) 
        page.setTotal(count(query, clazz));
        Pageable pageable = PageRequest.of((int) (page.getCurrent()+1), (int) page.getSize());
        List<T> records = template.find(query.with(pageable), clazz);
        page.setPages(page.getPages());
        page.setRecords(records);
        return page;
    


测试用例代码


import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.annotation.NoToken;
import org.springblade.core.tool.api.R;
import org.springblade.workface.modules.automate.Inertialnavigation.entity.InertialNavigation;
import org.springblade.workface.util.MongoDBUtil;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@AllArgsConstructor
@RequestMapping("inertialNavigation")
@Api(value = "惯导数据mongo测试", tags = "惯导数据mongo测试")
@NoToken
public class InertialNavigationController 

    @PostMapping("/save")
    @ApiOperation(value = "新增")
    private R<Boolean> save(@RequestBody InertialNavigation dto)
        MongoDBUtil.save(dto);
       return R.status(true);
    

    @PostMapping("/update")
    @ApiOperation(value = "修改")
    private R<Boolean> update(@RequestBody InertialNavigation dto)
        return R.status(MongoDBUtil.updateById(dto));
    

    @PostMapping("/remove")
    @ApiOperation(value = "删除")
    private R<Boolean> remove(@RequestBody List<Long> ids)
        MongoDBUtil.removeByIds(ids,InertialNavigation.class);
        return R.status(true);
    

    @PostMapping("/list")
    @ApiOperation(value = "查询")
    private R<List<InertialNavigation>> list()
        return R.data(MongoDBUtil.list(InertialNavigation.class));
    

    @GetMapping("/get/id")
    @ApiOperation(value = "详情")
    private R<InertialNavigation> get(@PathVariable("id") Long id)
        return R.data(MongoDBUtil.getById(id, InertialNavigation.class));
    


    @PostMapping("/page")
    @ApiOperation(value = "分页")
    private R<IPage<InertialNavigation>> page(@RequestBody Query query)
        return  R.data(MongoDBUtil.page(Condition.getPage(query),InertialNavigation.class));
    




InertialNavigation 代码

import lombok.Data;

import java.math.BigDecimal;
import java.util.Date;

@Data
public class InertialNavigation 
    private Long id;
    /** 支架数量 */
    private Integer zjsl;

    private Integer receivedFrame;
    private Integer sentFrame;
    private String zjh;
    /** 采煤机当前所在液压支架号 */
    private String zgbh;
    private BigDecimal speedResource;
    private Integer pingFlag;
    private String workTime;
    private Date startDate;
    private Integer direction;

    private InertialNavigationData newestResource;




InertialNavigationData 代码

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.math.BigDecimal;
import java.util.Date;


/**
 *  惯导数据实体类
 *
 * @version 1.0
 * @since JDK1.8
 * @author tarzan
 * @date 2022年01月29日 14:42:04
 */
@Data
public class InertialNavigationData 

    /** 主键 */
    private Long id;

    /** 惯导id */
    private Long InertialNavigationId;
    /** 基准x坐标 */
    private BigDecimal baseX;
    /** 基准y坐标 */
    private BigDecimal baseY;
    /** 基准z坐标 */
    private BigDecimal baseZ;
    /** x坐标 */
    private BigDecimal x;
    /** y坐标 */
    private BigDecimal y;
    /** z坐标 */
    private BigDecimal z;
    /** 计算x坐标 */
    private BigDecimal computeX;
    /** 计算y坐标 */
    private BigDecimal computeY;
    /** 计算z坐标 */
    private BigDecimal computeZ;
    private String guandaoType;
    private String guandaoTypeName;
    private String guandaoStatus;
    private String guandaoStatusName;
    private String gpsEnable;
    private String totalIndex;
    private BigDecimal fuyang;
    private BigDecimal henggong;
    private BigDecimal hangxiang;
    private String lcjs;
    /** 时间 */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createDate;
    /** 时间 */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updateDate;


以上是关于Springboot 整合mongodb 操作工具类仿mybatis-plus风格的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合MongoDB实战

SpringBoot整合MongoDB及简单的操作

SpringBoot整合MongoDB及简单的操作

SpringBoot整合MongoDB及简单的操作

springboot整合mybatis,mongodb,redis

springboot 整合 mongodb实现 批量更新数据