如何使用注解配置的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 cannot cast/convert those types unless you tell it how. All you need is a simple custom type handler.

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

select * from table_name where 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