buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

Mybatisplus TableInfoHelper:获取entity对应的数据表字段列表

如题,调用 TableInfoHelper#getTableInfo(clazz) 这个工具方法可以得到entity类所对应的数据表的字段列表。

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;


    TableInfo tableInfo = TableInfoHelper.getTableInfo(ScbgPayOrder.class);
    // 输出字段列表
    if (tableInfo != null) {
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        for (TableFieldInfo field : fieldList) {
            System.out.println("Column Name: " + field.getColumn());
        }
    } else {
        System.out.println("Table not found");
    }

 

 

代码中的ScbgPayOrder类有如下field。

 

注意到 entity 中使用的 @TableField注解:

  1. openid有 @TableField(exist = false) 声明,这表示 openid 不是数据表字段。则输出的结果里不会包含openid。
  2. passengerId 通过@TableField#value 声明了对应的字段名是“passenger_id1”。则输出的字段名即是“passenger_id1”。

 

下面是debug出来的TableInfo。

 

 

需要指明的一点是,TableInfoHelper 的 getTableInfo 依赖内部的一个map`TABLE_INFO_CACHE`, 这个map是Mybatisplus框架在容器启动的时候进行初始化的。 所以,不能直接通过下面的main方法来试图查看实体类的tableInfo信息。

public static void main(String[] args) {
    TableInfo tableInfo = TableInfoHelper.getTableInfo(LevyAccountRecharge.class);
    System.out.println(tableInfo.getIdType()); // 此时因 tableInfo 是null 而会抛NPE
}

当然,TableInfoHelper 里有一个 initTableInfo 方法,用来填充这个map。这个方法就是Mybatisplus框架在容器启动的时候所调用的。
因此,可以改变上面的main方法来查看实体类的tableInfo信息。

public static void main(String[] args) {
    TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""), LevyAccountRecharge.class);
    TableInfo tableInfo = TableInfoHelper.getTableInfo(LevyAccountRecharge.class);
    System.out.println(tableInfo.getIdType()); // 返回实际的IdType值
}

 

posted on 2024-10-23 19:45  buguge  阅读(613)  评论(0)    收藏  举报