Spring Boot和MongoDB的使用

MongoDB整合Spring Boot

pom.xml

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

application.properties

// 有密码
spring.data.mongodb.uri: mongodb://用户名:密码@ip:端口/数据库
// 无密码
spring.data.mongodb.uri: mongodb://ip:端口/数据库

实体类

@Getter
@Setter
@ToString
public class BlockDTO {
	@Id
    private String blockId;
    private String userId;
    private int belong;
    private int mode;
    private int status;
    private String title;
    private String content;
}

数据操作

@Component
@Slf4j
public class BlockImpl {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存数据
     * @param blockDTO
     * @return
     */
    public ResponseData saveBlock(BlockDTO blockDTO) {
        BlockDTO dto = mongoTemplate.insert(blockDTO);
        return ResponseData.ok().setData(dto);
    }
    /**
     * 修改数据
     * @param blockId
     * @param blockDTO
     * @return
     */
    public ResponseData updateBlock(String blockId, BlockDTO blockDTO) {
        BlockDTO block = mongoTemplate.findById(blockId, BlockDTO.class);
        if (block == null) {
            return ResponseData.ok(GlobalStatusCode.NOINFO.getMessage());
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(block.getBlockId()));
        Update update = new Update();
        update.set("title", "你好呀");
        UpdateResult dto = mongoTemplate.upsert(query, update, BlockDTO.class);
        return ResponseData.ok().setData(dto);
    }

    /**
     * 删除数据
     * @param blockId
     * @return
     */
    public ResponseData deleteBlock(String blockId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(blockId));
        if (!mongoTemplate.exists(query, BlockDTO.class)) {
            return ResponseData.ok(GlobalStatusCode.NOINFO.getMessage());
        }
        mongoTemplate.remove(query, BlockDTO.class);
        return ResponseData.ok();
    }

    /**
     * 按条件分页查询数据
     * @param jsonObject
     * @return
     */
    public ResponseData findBlockList(JSONObject jsonObject) {
        JSONObject res = new JSONObject();
        int pageNum = jsonObject.containsKey("pageNum") ? jsonObject.getInteger("pageNum") : 1;
        int pageSize = jsonObject.containsKey("pageSize") ? jsonObject.getInteger("pageSize") : 10;
        if (jsonObject.containsKey("userId") && "".equals(jsonObject.get("userId"))) {
            return ResponseData.error(GlobalStatusCode.MISSPARAMTER);
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(jsonObject.get("userId")));
        query.addCriteria(Criteria.where("status").is(0));

        Criteria criteria = Criteria.where("userId").is(jsonObject.get("userId"));
        criteria.and("status").is(0);
        if (jsonObject.containsKey("mode") && jsonObject.getInteger("mode") != 0) {
            criteria.and("mode").is(jsonObject.get("mode"));
            query.addCriteria(Criteria.where("mode").is(jsonObject.get("mode")));
        }

        Aggregation agg = newAggregation(
                match(criteria),
                skip((pageNum - 1) * pageSize),
                limit(pageSize)
        );
        long total = mongoTemplate.count(query, BlockDTO.class);
        AggregationResults<BlockDTO> aggregationResults = mongoTemplate.aggregate(agg,"blockDTO", BlockDTO.class);
        ArrayList arrayList = (ArrayList) aggregationResults.getRawResults().get("results");
        res.put("total", total);
        res.put("blockList", arrayList);
        return ResponseData.ok().setData(res);
    }

    /**
     * 详情查询
     * @param blockId
     * @return
     */
    public ResponseData findBlockById(String blockId) {
        BlockDTO block = mongoTemplate.findById(blockId, BlockDTO.class);
        if (block == null) {
            return ResponseData.ok(GlobalStatusCode.NOINFO.getMessage());
        }
        return ResponseData.ok().setData(block);
    }

    /**
     * 分组查询标题
     * @param jsonObject
     * @return
     */
    public ResponseData findTitleList(JSONObject jsonObject) {
        if (!jsonObject.containsKey("userId") && "".equals(jsonObject.get("userId"))) {
            return ResponseData.error(GlobalStatusCode.MISSPARAMTER);
        }
        Aggregation agg = newAggregation(
                match(new Criteria("userId").is(jsonObject.get("userId")).and("status").is(0).and("mode").is(1)),
                group("belong").push("$$ROOT").as("block")
        );
        AggregationResults<BlockDTO> aggregationResults = mongoTemplate.aggregate(agg,"blockDTO", BlockDTO.class);
        ArrayList arrayList = (ArrayList) aggregationResults.getRawResults().get("results");
        return ResponseData.ok().setData(arrayList);
    }
}

你可能感兴趣的:(spring,boot,mongodb,后端)