首頁 > 軟體

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

2022-06-06 22:01:13

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 == @com.weather.weatherexpert.common.utils.City@XINZHOU.getName"><!--right-->
	area_table
</if>
 
where 1=1
<if test="cityName == @com.weather.weatherexpert.common.utils.City@XINZHOU.getName"><!--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 == @com.a.b.c.CityClass$CityEnum@XINZHOU.getName"><!--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");

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com