1. 前 言
在实际的开发中,有时候我们会遇到动态建表的情况,什么意思呢?
解释一下,就是指根据传入的表名,动态地创建数据库表,以供后面的业务场景使用。
而使用 Mybatis 的动态 SQL,就能很好地为我们解决这个问题。
例如,现在要动态地创建一个班级表,那么正常的数据库语句,可能是这样的:
CREATE TABLE `2201011` (
`class_id` int(8) NOT NULL COMMENT' 班级id',
`class_name` varchar(100) NOT NULL COMMENT '班级名称',
`student_count` int(10) NOT NULL COMMENT '班级学生人数',
`teacher_count` int(8) NOT NULL COMMENT '班级配备教师人数',
PRIMARY KEY (`class_id`)
) ENGINE InnoDB CHARACTER SET utf8 COLLATE utf8_bin;
表名就是班级名,后面这个班级名是动态传参的,而每个班级都是这样的表结构字段,那接下来,我们就用 Mybatis 的动态 SQL 实现一下。
2. 动态建表实现
这里省略建立项目的过程,只写一个动态建表的实现。
Mapper 层
package springboot.mybatisplus.student.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import springboot.mybatisplus.student.entity.Student;
/**
* <p>
* Mapper 接口
* </p>
*
* @author yuhuofei
* @since 2022-04-05
*/
public interface StudentMapper extends BaseMapper<Student> {
/**
* 动态建表
*
* @param tableName
* @return int
*/
int createNewTable(@Param("tableName") String tableName);
}
Mapper.xml 层
<?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="springboot.mybatisplus.student.mapper.StudentMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="springboot.mybatisplus.student.entity.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="tid" property="tid"/>
</resultMap>
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
id, name, tid
</sql>
<update id="createNewTable" parameterType="String">
CREATE TABLE ${tableName} (
class_id int(8) NOT NULL ,
class_name varchar(100) NOT NULL ,
student_count int(10) NOT NULL ,
teacher_count int(8) NOT NULL ,
PRIMARY KEY (class_id)
)ENGINE InnoDB CHARACTER SET utf8 COLLATE utf8_bin
</update>
</mapper>