Mybatis如何优雅地进行时间条件查询?

在使用Mybatis进行搜索的时候,可以动态查询所有的条件。
比如:

<select id="selectByModelVague" parameterType="com.test.model.User" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from User
    <where>
      <if test="userState != null">
        user_state = #{userState}
      </if>
      <if test="userGender != null">
        and user_gender = #{userGender}
      </if>
      <trim prefix="and (" suffix=")" prefixOverrides="and|or">
        <if test="userNickName != null">
          user_nick_name = #{userNickName}
        </if>
        <if test="userRealName != null">
          or user_real_name = #{userRealName}
        </if>
      </trim>
    </where>
  </select>

通过这样的方式,就可以很方便地进行条件查询,如果你想根据性别搜索,只需要在传入的model中加入性别的属性就可以了!但是时间就不太一样了。

因为,时间的限制条件千奇百怪,可能有这样的:

<if test="startTime != null">
  and startTime > #{startTime}
</if>

也有可能有这样的:

<if test="startTime != null">
  and startTime < #{startTime}
</if>

甚至可能会有这样的:

<if test="startTime != null">
  and startTime > #{startTime} and endTime < #{startTime}
</if>

总之,时间不能像普通变量那样,可以直接一次性写好,就可以动态调用了。因为时间的查询条件可能性太多了。这种时候,就只能根据时间搜索条件的不同,来额外多写很多的查询方法。

那么,我的问题是,是否有什么工具或者方法,可以实现不用修改mapping文件,就可以实现优雅地进行时间搜索?

阅读 14.2k
2 个回答

要么这样:

public class UserQueryCommand {
    private Date startTime;
    private String startTimeOperator; // eq, lt, lte, gt, gte
}
// 伪代码
if startTime != null and startTimeOperator == 'eq'
    then xxx.startTime = #{startTime}
if startTime != null and startTimeOperator == 'lt'
    then xxx.startTime < #{startTime}
...

不过我都是这样:

public class UserQueryCommand {
    private Date startTimeEq;
    private Date startTimeLt;
    private Date startTimeLte;
    private Date startTimeGt;
    private Date startTimeGte;
}
// 伪代码
if startTimeEq != null
    then xxx.startTime = #{startTime}
if startTimeLt != null
    then xxx.startTime < #{startTime}
...

eq: =, lt: <, gt: >, lte: <=, gte: >=

其实mybatis没有 ibatis 的isnotempty方法,但是解决这样我是在service中先判断一手starttime,在查询
mybatis 的动态sql标签元素少

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题