Bootstrap

[DB] Mybatis-Plus 代码生成器AutoGenerator生成实体类字段顺序和DB表字段顺序不符

Mybatis-Plus提供的代码生成器AutoGenerator非常方便开发,但最近在使用过程中出现问题(因为有些场景是需要严格保证字段顺序的时候就很麻烦了):

生成实体类字段顺序表字段顺序不符,我以Sql Server数据库举例说明。

生成器获取表字段源码

DataSourceConfig有一属性,IDbQuery,查看其内容:

这个类的有个方法叫tableFieldsSql,表字段信息查询 SQL,默认实现了主流数据库表字段获取方法(DB2Query,SqlServerQuery等):

知道原理就好解决了,直接上代码

解决办法

重写SqlServerQuery的tableFieldsSql方法,注意跟原来对比,默认我增加了排序:

+ " ORDER BY b.column_id";

package com.song.devtool.util;

import com.baomidou.mybatisplus.generator.config.querys.SqlServerQuery;

public class SqlServerQueryOrdered extends SqlServerQuery {
    @Override
    public String tableFieldsSql() {
        System.out.println("+++++++++++++++++++++++++++++ Customized SqlServerQueryOrdered +++++");
        return "SELECT  cast(a.NAME AS VARCHAR(500)) AS TABLE_NAME,cast(b.NAME AS VARCHAR(500)) AS COLUMN_NAME, "
            + "cast(c.VALUE AS VARCHAR(500)) AS COMMENTS,cast(sys.types.NAME AS VARCHAR (500)) AS DATA_TYPE,"
            + "(" + " SELECT CASE count(1) WHEN 1 then 'PRI' ELSE '' END"
            + " FROM syscolumns,sysobjects,sysindexes,sysindexkeys,systypes "
            + " WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id (A.NAME) AND sysobjects.xtype = 'PK'"
            + " AND sysobjects.parent_obj = syscolumns.id " + " AND sysindexes.id = syscolumns.id "
            + " AND sysobjects.NAME = sysindexes.NAME AND sysindexkeys.id = syscolumns.id "
            + " AND sysindexkeys.indid = sysindexes.indid "
            + " AND syscolumns.colid = sysindexkeys.colid AND syscolumns.NAME = B.NAME) as 'KEY',"
            + "  b.is_identity isIdentity "
            + " FROM ( select name,object_id from sys.tables UNION all select name,object_id from sys.views ) a "
            + " INNER JOIN sys.COLUMNS b ON b.object_id = a.object_id "
            + " LEFT JOIN sys.types ON b.user_type_id = sys.types.user_type_id   "
            + " LEFT JOIN sys.extended_properties c ON c.major_id = b.object_id AND c.minor_id = b.column_id "
            + " WHERE a.NAME = '%s' and sys.types.NAME !='sysname' "
            + " ORDER BY b.column_id";
    }
}

然后配置到DataSourceConfig:dsc.setDbQuery(new SqlServerQueryOrdered());

可以看到字段顺序恢复了。(注意重新生成的时候,一定要把原来的文件删掉,不然不会覆盖文件内容)

 

see you!!! 

;