java
  • mybatis
  • ibatis
  • 2017-08-31 7 views 0 likes 
    0

    null値を渡す場合、MyBatisにjava.util.Date INパラメータに使用するdb-typeを明示的に伝える必要があるようです。しかし、私はそれを行う方法を見つけることができません。注釈が設定されたMyBatisで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) 
    

    はどのようにして、パラメータの型を指定していますか?

    答えて

    1

    他の開発者は既にこの種の問題についてコメントしています。

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

    選択* ID =#{値、typeHandler = StrToIntTypeHandler}

    だから今は、あなたがそのようなカスタムtypehandler作成する場合table_nameのから:

    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: [email protected], i: 1, param: null, type: OTHER 
    DEBUG [main] - ==> Parameters: null, null 
    ps: [email protected], i: 2, param: null, type: OTHER 
    DEBUG [main] - <==  Total: 0 
    
    関連する問題