如何为mybatis-spring-boot映射EnumOrdinalTypeHandler?

问题描述 投票:2回答:2

我现在正在使用Mybatis和spring-boot。我没有添加mybatis-config.xml。我通过application.propertiesmybatis-spring-boot-autoconfigure的指令进行数据源和mybatis的所有配置,如下所示

### Database Configuration
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=mywebsite;catalogName=mywebsite
spring.datasource.username=sa
spring.datasource.password=root
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver

### Mybatis Configurations ###
mybatis.type-aliases-package=com.mycom.myproducts.mywebsite.config.bean
mybatis.type-handlers-package=org.apache.ibatis.type.EnumOrdinalTypeHandler
mybatis.mapperLocations=classpath:mybatis/mapper/**/*.xml
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=30

问题是mybatis无法映射我的枚举类型和错误显示

Caused by: org.apache.ibatis.executor.result.ResultMapException: Error attempting to get column 'gender' from result set.  
Cause: java.lang.IllegalArgumentException: No enum constant com.mycom.myproducts.mywebsite.config.bean.config.UserBean.Gender.0

这可以通过mybatis-config.xml修复

    <typeHandlers>
       <typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.mycom.myproducts.mywebsite.config.bean.config.UserBean$Gender"/>
    </typeHandlers>

但我不知道application.properties文件怎么办呢?

mybatis spring-mybatis
2个回答
1
投票

试试这个

package com.example.typehandler;
@MappedTypes({Gender.class})
public class GenderTypeHandler extends EnumOrdinalTypeHandler {}

mybatis.type-handlers-package=com.example.typehandler

    @Select(...)
    @Results(value = {
             @Result(property="gender", column="gender", typeHandler="com.example.typehandler.Gender"),
             ...

如果你使用typeHandler@Result中的@MappedTypes可能是不必要的。


0
投票

您需要直接指定包而不是TypeHandler类。

所以你可以用它作为下一个:

mybatis.type-handlers-package=org.apache.ibatis.type

手册页说明了type-handlers-package get包来搜索类型别名。

type-handlers-package用于搜索类型处理程序的包。 (包分隔符是“,; \ t \ n”)

© www.soinside.com 2019 - 2024. All rights reserved.