我现在正在使用Mybatis和spring-boot。我没有添加mybatis-config.xml
。我通过application.properties
从mybatis-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
文件怎么办呢?
试试这个
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
可能是不必要的。
您需要直接指定包而不是TypeHandler类。
所以你可以用它作为下一个:
mybatis.type-handlers-package=org.apache.ibatis.type
手册页说明了type-handlers-package get包来搜索类型别名。
type-handlers-package用于搜索类型处理程序的包。 (包分隔符是“,; \ t \ n”)