Mybatis條件if test如何使用枚舉值

Mybatis條件if test使用枚舉值

1.正確

package com.weather.weatherexpert.common.utils;
/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @Author 
 * @CreateTime 
 */
public enum City {
    XINZHOU(100002,"忻州"),
    DATONG(100003,"大同"),
    TAIYUAN(100001,"太原");
 
    private final Integer code;
    private final String name;
 
    City(Integer value, String desc) {
        this.code = value;
        this.name = desc;
    }
 
    public Integer getCode() {
        return code;
    }
 
    public String getName() {
        return name;
    }
}

xml:

<!--<if test="cityName == @com.weather.weatherexpert.common.utils.City.XINZHOU@getName">&lt;!&ndash;wrong,java.lang.ClassNotFoundException: Unable to resolve class: com.weather.weatherexpert.common.utils.City.XINZHOU&ndash;&gt;-->
<!--<if test="cityName == @com.weather.weatherexpert.common.utils.City@XINZHOU@getName">&lt;!&ndash;wrong,[org.apache.ibatis.ognl.ParseException: Encountered " "@" "@ "" at line 1, column 65.&ndash;&gt;-->
<if test="cityName == @[email protected]"><!--right-->
	area_table
</if>
 
where 1=1
<if test="cityName == @[email protected]"><!--right-->
	and city_name=#{cityName}
</if>	

2.錯誤

package com.weather.weatherexpert.common.utils;
/**
 * <p>Title: </p>
 * <p>Description: </p>
 *
 * @Author
 * @CreateTime
 */
public class CityClass {
    public static enum CityEnum {
 
        XINZHOU(100002, "忻州"),
        DATONG(100003, "大同"),
        TAIYUAN(100001, "太原");
 
        private final Integer code;
        private final String name;
 
        CityEnum(Integer value, String desc) {
            this.code = value;
            this.name = desc;
        }
 
        public Integer getCode() {
            return code;
        }
 
        public String getName() {
            return name;
        }
    }
}

xml:

/*        Caused by: org.apache.ibatis.builder.BuilderException: Error evaluating expression
        'cityName == @com.weather.weatherexpert.common.utils.CityClass@CityEnum.XINZHOU.getName'. Cause: org.apache.ibatis.ognl.OgnlException:
        Could not get static field CityEnum from class com.weather.weatherexpert.common.utils.CityClass [java.lang.NoSuchFieldException: CityEnum]*/
        <if test="cityName == @com.weather.weatherexpert.common.utils.CityClass@CityEnum.XINZHOU.getName"><!--wrong-->
            area_table
        </if>	

可見,直接定義的枚舉類可以正常使用,在類中定義的枚舉類這樣使用會報錯,可能方法還沒有找到。

如下正確:

 <if test="cityName == @[email protected]"><!--right-->
  name = #{username}
 </if>

Mybatis裡使用枚舉Enum判斷

<if test="dtEnum == @com.xxx.xxx.TestTypeEnum@HOUR">
  DATE_FORMAT(TM,'%Y-%m-%d %H') as keyStr,
</if>

TestTypeEnum定義如下

  • HOUR("hour"),
  • DAY("day"),
  • MONTH("month"),
  • YEAR("year");

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: