动态创建表

部分场景需要动态创建表,例如根据用户输入的表名动态创建。动态创建表可以使用xml方式来实现,具体步骤如下:

1、service层:中调用mapper里的createTable方法

     itemMapper.createItemTable(tableName, VARCHAR_256);

2、DAO层:mapper中写具体的创建方法 createItemTable

@Mapper
public interface ItemMapper {
    void createItemTable(String tableName,String type);
}
// 只有一个参数时,写成:void createItemTable( @Param("tableName")String tableName );

3、xml文件中编写建表语句

  • namespace:ItemMapper的路径
  • update id:createItemTable方法名
  • ${ }:用来使用传入的参数(注意不是#{})
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.datamanager.dal.mapper.ItemMapper">
    <!-- 创建表SQL,tableName为表名,type为original_data字段类型-->
    <update id="createItemTable">
        create table ${tableName}
        (
        id          int unsigned not null auto_increment comment '自增主键ID',
        subset_id      int not null  default 0 comment '子集ID',
        name     varchar(64) not null default '' comment '数据名',
        original_data  ${type} not null default '' comment '原始数据',
        meta         varchar(1024) not null  default '' comment '元数据',
        status       tinyint not null  default 1 comment '状态',
        creator      varchar(32) not null  default '' comment '创建人',
        operator      varchar(32) not null  default '' comment '最后修改人',
        create_time datetime    not null default current_timestamp comment '创建时间',
        modify_time datetime   not null default current_timestamp on update current_timestamp comment '更新时间',
        primary key (`id`),
        unique key `uk_name`(`name`)
        )ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 comment '源数据表';
    </update>
</mapper>

参考资料

springboot+mybatis动态创建数据表和删除数据库表(流程)

MyBatis 动态创建表(详细一些) 

posted @ 2024-08-18 23:14  zhegeMaw  阅读(166)  评论(0)    收藏  举报