Criteria MongoTemplate 实现非无条件查询

问题描述

我是 Spring MongoDB Criteria 的初学者。

一旦我的数据库MysqL,如果变量不是 none,我可以这样做 not none query

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.mytest.modules.system.mapper.SysUserMapper">
    <select id="getSysUser" resultType="org.mytest.modules.system.entity.SysUser">
        select * from sys_user where del_flag = 0 
        <if test="username!=null and username!=''">
            and username = #{username}
        </if>
        <if test="age!=null and age!=''">
            and age = #{age}
        </if>
        <if test="profession!=null and profession!=''">
            and profession = #{profession}
        </if>
        <if test="education!=null and education!=''">
            and education = #{education}
        </if>
        <if test="dateStart!=null">
            <![CDATA[  and DATE_FORMAT(time,'%Y-%m-%d %H:%T:%s') >= 
            DATE_FORMAT(#{dateStart},'%Y-%m-%d %H:%T:%s') ]]>
        </if>
        <if test="dateEnd!=null">
            <![CDATA[  and DATE_FORMAT(time,'%Y-%m-%d %H:%T:%s') <= 
            DATE_FORMAT(#{dateEnd},'%Y-%m-%d %H:%T:%s') ]]>
        </if>
    </select>
</mapper>

现在我的数据库更改为 mongoDB。如何使用带有 Criteria().andOperator 的 Criteria MongoTemplate 来实现?

解决方法

        SysUser sysUser = new SysUser();
        // Create criteria object
        Criteria criteria = Criteria.where("del_flag").is(0);
        // Judge one by one
        if (StringUtils.hasLength(sysUser.getUsername())) {
            criteria = criteria.and("username").is(sysUser.getUsername());
        }
        if (Objects.nonNull(sysUser.getAge())) {
            criteria = criteria.and("age").is(sysUser.getAge());
        }
        if (StringUtils.hasLength(sysUser.getProfession())) {
            criteria = criteria.and("profession").is(sysUser.getProfession());
        }
        if (StringUtils.hasLength(sysUser.getEducation())) {
            criteria = criteria.and("education").is(sysUser.getEducation());
        }
        if (Objects.nonNull(sysUser.getDateStart())) {
            criteria = criteria.and("dateStart").gte(sysUser.getDateStart());
        }
        if (Objects.nonNull(sysUser.getDateEnd())) {
            criteria = criteria.and("dateEnd").lte(sysUser.getDateEnd());
        }
        Query query = new Query(criteria);
        List<SysUser> sysUserList = mongoTemplate.find(query,SysUser.class,"sys_user");