事先作成一 enum,如下:
public enum CityCode {
ALL("000"),
BEIJING("010"),
SHANGHAI("021"),
private String code;
CityCode(String code) {
this.code = code;
}
public String val() {
return this.code;
}
}
在mapper檔案中,想判斷一個參數的值是否跟
CityCode.ALL
的值一緻的時候,我想當然的像下面這麼寫了:
<if test="area != com.test.constant.CityCode.ALL.val" >
AND
p.`city`=#{area}
</if>
我為什麼會這麼寫?
因為之前有在 mapper 檔案中判斷過
List
對象的size 是不是為 0的,就是下面這麼寫的:
<if test="statusList.size > 0" >
// to do sth.
</if>con
但是,結果是行,mybatis 報了下面的錯:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.binding.BindingException: Parameter 'com' not found. Available parameters are [area, param1, param2, now]
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:) ~[mybatis-spring-.jar:]
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:) ~[mybatis-spring-.jar:]
at com.sun.proxy.$Proxy22.selectList(Unknown Source) ~[?:?]
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:) ~[mybatis-spring-.jar:]
at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:) ~[mybatis-.jar:]
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:) ~[mybatis-.jar:]
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:) ~[mybatis-.jar:]
at com.sun.proxy.$Proxy38.performance(Unknown Source) ~[?:?]
後來,又想起來,之前有過在 mybatis 中通路靜态方法的示例,試了一下,果然可以,enum 修改如下:
public enum CityCode {
ALL("000"),
BEIJING("010"),
SHANGHAI("021"),
private String code;
CityCode(String code) {
this.code = code;
}
public String val() {
return this.code;
}
public static boolean isAll(String code) {
return ALL.val().equals(code);
}
}
然後,mapper 檔案修改如下:
<if test="[email protected]@isAll(area)" >
AND
p.`city`=#{area}
</if>
請注意一下文法:
@[email protected](parameter)
我上面那個test部分的第一個 ! 是用來對結果取反的,它不屬于文法的一部分。當然,你可以不用 ! 改用 not 也一樣的。