如何解决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");
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。