在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  網(wǎng)絡(luò)安全/ Mybatis如何優(yōu)雅地進行時間條件查詢?

Mybatis如何優(yōu)雅地進行時間條件查詢?

在使用Mybatis進行搜索的時候,可以動態(tài)查詢所有的條件。
比如:

<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>

通過這樣的方式,就可以很方便地進行條件查詢,如果你想根據(jù)性別搜索,只需要在傳入的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>

總之,時間不能像普通變量那樣,可以直接一次性寫好,就可以動態(tài)調(diào)用了。因為時間的查詢條件可能性太多了。這種時候,就只能根據(jù)時間搜索條件的不同,來額外多寫很多的查詢方法。

那么,我的問題是,是否有什么工具或者方法,可以實現(xiàn)不用修改mapping文件,就可以實現(xiàn)優(yōu)雅地進行時間搜索?

回答
編輯回答
涼薄

其實mybatis沒有 ibatis 的isnotempty方法,但是解決這樣我是在service中先判斷一手starttime,在查詢
mybatis 的動態(tài)sql標(biāo)簽元素少

2017年8月14日 00:52
編輯回答
撿肥皂

要么這樣:

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: >=

2017年7月7日 10:23