MyBatis Generator:解决tinyint映射成boolean/byte的问题

当MySQL中的字段类型为tinyint(4)时,使用MyBatis Generator生成的实体类对应的字段类型为:Byte

问题是什么产生的?

MyBatis Generator 是通过 JavaTypeResolver 来实现关系映射的,官方文档解释:

The element is used to define properties of the Java Type Resolver. The Java Type Resolver is used to calculate Java types from database column information. The default Java Type Resolver attempts to make JDBC DECIMAL and NUMERIC types easier to use by substituting Integral types if possible (Long, Integer, Short, etc.) If this behavior is undesirable, set the property "forceBigDecimals" to "true". You can also substitute your own implementation if you want different behavior than the default. This element is an optional child element of the element.

综上所得,问题可能是JavaTypeResolver默认的配置存在问题。查看源码后发现确实如此:
image

解决问题

如果只有个别字段存在问题,可以通过配置columnOverride实现,在generatorConfig.xml文件中,修改:

<table schema="xxx" tableName="xxx" >
        <columnOverride column="xxx" property="xxx" javaType="java.lang.Integer"/>
        <columnOverride column="is_del" property="isDel" javaType="java.lang.Integer"/>
</table>

如果觉得麻烦,可以通过覆盖javaTypeResolver的配置实现:

  1. 在官网可以看到,javaTypeResolver有一个type属性,用于配置Java Type Resolver

  2. 创建一个继承JavaTypeResolverDefaultImpl的类,并写入:

public class MyJavaTypeResolver extends JavaTypeResolverDefaultImpl {
    public MyJavaTypeResolver(){
        super();
        typeMap.put(-6, new JavaTypeResolverDefaultImpl.JdbcTypeInformation("TINYINT", new FullyQualifiedJavaType(Integer.class.getName()))); // 当类型为TINYINT时,则生成的Java类型为Integer
    }
}
  1. 在配置文件中,添加:
<!-- 指定 MyJavaTypeResolver 的路径 -->
<javaTypeResolver type="top.testops.mbg.MyJavaTypeResolver" />
  1. 重新执行MyBatisGenerator,即可看到新生成的实体类中,TINYINT会转为Integer
posted @ 2021-09-09 14:38  Feng1024  阅读(3447)  评论(0编辑  收藏  举报