关于mybatis动态创建数据库表的相关操作

首先说说我这个项目中遇到的问题

开发的是自定义表单的功能,我也是第一次遇到需要这种类似的问题 : 需要动态的根据用户在页面设计的表单在数据库创建对应的数据库表

设计页面如下: (本人前端页面写的很烂,大家轻喷)















大家只要知道下面设计部分可以自定义列名和类型就可以了

然后后台框架用的是mybatis , 不遇到这个需求的话我还真没发现mybatis并没有有关建表的功能

然后在开发中各种花式报错 很难受 

然后经过一系列的测试发现 如果直接写完整的SQL语句 是可以成功运行的

这是建好的表

而且只有update标签可以正常运行!!  select insert delete sql 均不可以 这点可以研究下源码看看到底是为什么


但是这仅仅是创建一个死表 并不是我们想要的效果  接下来我这样试试

  <update   id="createDemo">
  		CREATE TABLE ${tableName} (
    		id int primary key auto_increment,
    		applicant varchar(10) not null,
    		createTime timestamp ,
       		isdel tinyint not null
      )character set utf8 collate utf8_bin;
  </update>

测试结果是可行的 说明表名是可以动态插入的  那么字段名和字段类型呢 我把sql改成这样

  <update   id="createDemo">
  		CREATE TABLE ${tableName} (
    		
    		${filedName} varchar(10) not null
    		
      )character set utf8 collate utf8_bin;
  </update>

测试结果也是可以的


那如果我再加上类型呢?

<update   id="createDemo">
  		CREATE TABLE ${tableName} (
    		
    		${filedName} ${type}(10) not null
    		
      )character set utf8 collate utf8_bin;
  </update>

测试结果就不发了 也是可以的


经过一段时间测试后我的第一个版本的sql是这样的

  <update id="createTable" statementType="STATEMENT" parameterType="map">  
    CREATE TABLE ${tableName}  (
    		id int primary key auto_increment,
    		applicant varchar(10) not null,
    		createTime timestamp ,
       		isdel tinyint not null,
       <foreach collection="list" item="flowtable" separator="," >
       
       	<choose>
       		<when test="flowtable.mycolumn != null and flowtable.mycolumn !=''">${flowtable.mycolumn}</when>
       		<otherwise>${flowtable.id}</otherwise>
       	</choose>
       		 ${flowtable.texttype}<if test="flowtable.max != null">(${flowtable.max})</if>  <!-- <if test="flowtable.isnull != 0">not null</if> -->
       </foreach>
      )character set utf8 collate utf8_bin;
  </update>

是可用的  后来发现把  statementType="STATEMENT" 去掉也是可以使用的

我也不知道为什么 前期测试时不加这 statementType="STATEMENT" 是没法使用的 但是后来写博客的时候却又可以了 可能但是测试时太着急哪里出问题了吧

如果有朋友遇到同样的问题可以加上 statementType="STATEMENT"试试

最后 很简单的功能我却花了很大的功夫才搞完 心态崩了  希望再遇到类似功能的朋友多留心




发布了16 篇原创文章 · 获赞 21 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/q690080900/article/details/76228208