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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM