2012-11-20 30 views
3

我在我的项目中使用MyBatis与MySql。MyBatis Java布尔到Sql枚举

我:

MyField的ENUM( '是', '否')

,我想在映射到Java布尔值:

我知道我可以修改所有的MyBatis模板,例如:

<update id="update"> 
UPDATE 
myTable 
    <set> 
     ... 
     <if test="myField != null">myField = <choose> 
      <when test="myField == true">'yes'</when> 
      <otherwise>'no'</otherwise> 
      </choose>, 
     </if> 
     ... 
    </set> 
WHERE 
    ... 
</update> 

但我可以用更方便的方法吗?

回答

10

这似乎解决了,这是实现我自己的布尔类型处理器的最好方法:

public class YesNoBooleanTypeHandler extends BaseTypeHandler<Boolean> { 

    @Override 
    public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter,  JdbcType jdbcType) 
      throws SQLException { 
     ps.setString(i, convert(parameter)); 
    } 

    @Override 
    public Boolean getNullableResult(ResultSet rs, String columnName) 
      throws SQLException { 
     return convert(rs.getString(columnName)); 
    } 

    @Override 
    public Boolean getNullableResult(ResultSet rs, int columnIndex) 
      throws SQLException { 
     return convert(rs.getString(columnIndex)); 
    } 

    @Override 
    public Boolean getNullableResult(CallableStatement cs, int columnIndex) 
      throws SQLException { 
     return convert(cs.getString(columnIndex)); 
    } 

    private String convert(Boolean b) { 
     return b ? "yes" : "no"; 
    } 

    private Boolean convert(String s) { 
     return s.equals("yes"); 
    } 

} 

,然后在模板映射使用它:

<update id="update"> 
UPDATE 
myTable 
    <set> 
     ... 
     <if test="myField != null">myField = #{myField ,typeHandler=YesNoBooleanTypeHandler}</if> 
     ... 
    </set> 
WHERE 
    ... 
</update>