背景
<if test="aggByAdDate">
<choose>
<when test="granularity == @com.example.enums.Granularity@DAY">
DATE(record_time),
</when>
<when test="granularity == @com.example.enums.Granularity@HOUR">
DATE_FORMAT(record_time,'%Y-%m-%d %H'),
</when>
<otherwise>
record_time,
</otherwise>
</choose>
</if>
@Getter
@AllArgsConstructor
public enum Granularity implements EnumBase {
/**
* 时间粒度.
*/
DAY(1, "天级") {
@Override
public LocalDateTime truncate(LocalDateTime dateTime) {
return dateTime.truncatedTo(ChronoUnit.DAYS);
}
@Override
public LocalDateTime plus(LocalDateTime dateTime, int delta) {
return dateTime.plusDays(delta);
}
}
}
上面MyBatis的mapper xml定义会出现下面的异常:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: java.lang.IllegalArgumentException: invalid comparison: com.example.enums.Granularity$3 and com.example.enums.Granularity$1
### Cause: java.lang.IllegalArgumentException: invalid comparison: com.example.enums.Granularity$3 and com.example.enums.Granularity$1
分析和问题分解
1、考虑到是否为依赖包版本的问题,导致类型不兼容的问题
2、在相应的堆栈打上断点,查看具体的值和类型
问题解决记录
1、回退之前的版本是可以成功执行
2、对比现今版本,主要是枚举在声明时进行了方法重写。
3、在相应的堆栈打上断点,查看具体的值和类型。
结果:两个枚举的值的类型不一致,导致Ognl无法进行比较。
4、为什么会出现类型不一致呢?
枚举重写方法时,会生成相应的匿名类,导致每个枚举的类型和原类型不一致,从而导致比较时出现不兼容的现象
解决:
<if test="aggByAdDate">
<choose>
<when test="granularity.code == @com.example.enums.Granularity@DAY.getCode()">
DATE(record_time),
</when>
<when test="granularity.code == @com.example.enums.Granularity@HOUR.getCode()">
DATE_FORMAT(record_time,'%Y-%m-%d %H'),
</when>
<otherwise>
record_time,
</otherwise>
</choose>
</if>