簡體   English   中英

如何使用注釋配置的MyBatis指定IN參數類型

[英]How to specify IN param type with annotation-configured MyBatis

如果我想能夠傳遞空值,似乎我需要明確告訴MyBatis用於java.util.Date IN參數的數據庫類型。 但是我找不到這樣做的方法。

我沒有運氣就嘗試了以下各種變化:

@Select("<script>SELECT ... WHERE ... " +
    "<if test='#{dateFrom,jdbcType=TIMESTAMP} != null'>" +
    "  AND date &gt; #{dateFrom,jdbcType=TIMESTAMP}" + 
    "</if></script>")
List<MyType> getRecords(@Param("dateFrom") dateFrom)

使用注釋時如何指定參數類型?

其他開發人員已經對這種問題發表了評論。

我引用GitHub評論:

@nglsatheesh MyBatis不能強制轉換/轉換這些類型,除非您告訴它如何。 您只需要一個簡單的自定義類型處理程序。

public class StrToIntTypeHandler implements TypeHandler<String> {
  @Override
  public void setParameter(PreparedStatement ps, int i,
      String parameter, JdbcType jdbcType) throws SQLException {
    ps.setInt(i, Integer.parseInt(parameter));
  }
  // other methods are for binding query results.
}

從table_name中選擇*,其中id =#{value,typeHandler = StrToIntTypeHandler}

所以現在,如果您要創建這樣的自定義類型處理程序:

public class Null2DateTypeHandler implements TypeHandler<Date> {

    @Override
    public void setParameter(PreparedStatement ps, int i, java.util.Date parameter, JdbcType jdbcType) throws SQLException {
        System.err.println(String.format("ps: %s, i: %d, param: %s, type: %s", ps.toString(), i, parameter, jdbcType.toString()));

        if (parameter == null) {
            ps.setDate(i, null); // ??? I'm not sure. But it works.
        } else {
            ps.setDate(i, new java.sql.Date(parameter.getTime()));
        }
    }
}

並且,映射器端:

@Select({
    "<script>"
    , "SELECT * FROM `employees` WHERE `hire_date` "
    , "  BETWEEN
    , "  #{dateFrom,typeHandler=*.*.*.Null2DateTypeHandler}"
    , "  AND"
    , "  #{dateTo,typeHandler=*.*.*.Null2DateTypeHandler}"      
    ,"</script>"
})
@Results({
      @Result(property = "empNo", column = "emp_no"),
      @Result(property = "birthDate", column = "birth_date"),
      @Result(property = "firstName", column = "first_name"),
      @Result(property = "lastName",  column = "last_name"),
      @Result(property = "gender",    column = "gender"),
      @Result(property = "hireDate",  column = "hire_date")          
})  
List<Employees> selectBetweenTypeHandler(@Param("dateFrom") Date dateFrom, @Param("dateTo") Date dateTo);

我的日志記錄,看起來工作正常。

DEBUG [main] - ==>  Preparing: SELECT * FROM `employees` WHERE `hire_date` BETWEEN ? AND ? 
ps: org.apache.ibatis.logging.jdbc.PreparedStatementLogger@369f73a2, i: 1, param: null, type: OTHER
DEBUG [main] - ==> Parameters: null, null
ps: org.apache.ibatis.logging.jdbc.PreparedStatementLogger@369f73a2, i: 2, param: null, type: OTHER
DEBUG [main] - <==      Total: 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM