项目中使用了TkMapper
实体类
public class Schedule {
@ColumnType(column = "schedule_types", typeHandler = ScheduleTypesHandler.class, jdbcType = JdbcType.VARCHAR)
private List<ScheduleType> scheduleTypes;
}
typeHandler对应的实现(内容省略)
public class ScheduleTypesHandler extends BaseTypeHandler<List<ScheduleType>> {
...省略一万字...
}
Mapper对应的类
public interface ScheduleMapper extends Mapper<Schedule> {
@Select({"SELECT * FROM ops_china_schedule"})
List<Schedule> selectConsSchedule();
}
东西写好了,看着没问题,那么我们来跑一下,调用selectConsSchedule()
结果
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'schedule_types' from result set. Cause: java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `xxx.entity.EvaluationReportResult` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('AUDIO')
at [Source: (String)"["AUDIO","VIDEO"]"; line: 1, column: 2] (through reference chain: java.util.ArrayList[0])
怎么回事,这么简单的一个查询,还报错了
那么
我们来看一下报的什么错,["AUDIO","VIDEO"]不能序列化成EvaluationReportResult
但EvaluationReportResult是什么鬼,查询的代码里面和这东西没有关系啊
那就只有1中可能了,typeHandler指定的Handler没生效
那怎么会没生效呢,在看一下
mybatis原生提供的是xml和@Select,xml需要在resultMap里面指定Handler,@Select需要用@Results里面指定Hanlder,而@ColumnType是TkMapper提供的
现在我们直接调用selectConsSchedule,没有经过TkMapper,直接调用了Mybatis原生方法,实体类中的Handler当然不会生效,于是当项目中有多个Handler时,就会出现有时候报错的情况
解决方案
如果使用的是@Select
那么只需要使用同样的方式加注解即可
@Select({"SELECT * FROM ops_china_schedule"})
@Results(
@Result(column = "schedule_types", property = "scheduleTypes", typeHandler = ScheduleTypesHandler.class)
)
List<Schedule> selectConsSchedule();
如果是使用xml,添加对应的配置即可
<resultMap id="xxx" type="xxx.Schedule">
<result property="scheduleTypes" column="schedule_types" typeHandler="xxx.typehandler.ScheduleTypesHandler"/>
</resultMap>
再运行一下,问题解决
本文介绍了一个关于MyBatis类型处理器未生效的问题及其解决办法。问题出现在使用@Select注解时,自定义的类型处理器未能正确处理查询结果。通过在@Select注解上添加@Results指定类型处理器,问题得以解决。

405

被折叠的 条评论
为什么被折叠?



