zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    C#中正则表达式的使用
    Asp.Net MVC 身份验证-Forms
    ASP.NET MVC:窗体身份验证及角色权限管理示例
    asp.net mvc forms身份认证
    ASP.NET MVC Form验证
    C#进阶系列——WebApi 接口返回值不困惑:返回值类型详解
    参考例子,学习Func<T, TResult>委托
    Razor 中的@helper 与 @function 用法
    @Helper辅助方法和@functions自定义函数
    ASP.NET MVC传递参数(model), 如何保持TempData的持久性
  • 原文地址:https://www.cnblogs.com/testopsfeng/p/15246828.html
Copyright © 2011-2022 走看看