springboot+mybatis实现代码创建数据库表

springboot+mybatis实现代码创建数据库表

这里呢我就不说原理啦,直接说怎样做,估计这个才会是你们想要的,话不多说上代码
首先呢 你要对sql的create创建表要非常的熟悉
在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="com.mr.create_able.mapper.TableMapper">

    <!--创建表的 SQL 语句-->
    <update id="createTable" parameterType="java.lang.String">
        CREATE TABLE IF NOT EXISTS `${tableName}`
        (
            `id`       int(0)      NOT NULL AUTO_INCREMENT COMMENT '主键',
            `group_id` int(0)      NULL DEFAULT NULL COMMENT '组号',
            `username` varchar(20) NULL DEFAULT NULL COMMENT '用户名',
            `password` varchar(20) NULL DEFAULT NULL COMMENT '密码',
            PRIMARY KEY (`id`)
        ) ENGINE = InnoDB
          AUTO_INCREMENT = 9
          CHARACTER SET = utf8mb4 COMMENT ='用于测试的用户表';
    </update>

</mapper>

表已经准备完毕,数据库连接我们是必须要有的

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: root
#thymeleaf:
#    cache: false
mybatis:
      mapper-locations: classpath:mapping/*Mapper.xml
      type-aliases-package: com.qg.pojo
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

别忘了编辑mapper.java写一个可以找到mapper.xml的接口

public interface TableMapper {
    /**
     * 创建数据库表
     *
     * @param tableName 表名称
     */
    void createTable(String tableName);
}

这些工作全部做好了,你就可以直接controller层直接测试啦

@RestController
@RequestMapping("/create")
public class TestController {
    @MyField()
    private String name;

    @Resource
    private TableMapper tableMapper;
    @Resource
    private CommonRepository commonRepository;
    @Resource
    private ObjectMapper objectMapper;
    @PostMapping("/createTable")
    public ResponseEntity<String> createTableTest(@RequestParam String tableName) {
        try {
            // 创建数据库表
            tableMapper.createTable(tableName);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("创建数据库表失败");
        }
        return ResponseEntity.ok("创建数据库表成功");
    }
}

这样用代码创建一个表就可以成功了
到了这里不知道大家会不会有一个疑问,因为代码创建表的场景,我们会作为月的记录表来用,那你在创建的时间是不是就要去判断一下这张表是不是已经存在了,所以你就要查看数据库中的表了,以下就是具体做法:

public interface SelectTbaleMapper {
    /**
     * 获取当前数据库表名
     *
     * @param tableNameList 表名列表
     * @return
     */
    List<String> getTableNameList(@Param("tableNameList") List<String> tableNameList);
}

这样的一个接口写完毕后呢,我们需要增加自己sql语句

<?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.mr.create_able.mapper.SelectTbaleMapper">

    <select id="getTableNameList" resultType="java.lang.String">
        select table_name from information_schema.tables where TABLE_SCHEMA=(select database())
        <if test="tableNameList !=null and tableNameList.size() > 0">
            and table_name in
            <foreach collection="tableNameList" item="item" separator="," open="(" close=")">
                #{item}
            </foreach>
        </if>
    </select>
</mapper>

这种是得到数据中所有的表的名称
具体实现:

    private ObjectMapper objectMapper;
    @RequestMapping("/getTable")
    public String getTableName() throws JsonProcessingException {
      return   objectMapper.writeValueAsString(commonRepository.getTableNameList(null));
    }

OK到这里就结束啦!我们下次再见,嘻嘻.

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值