【mybatis】利用动态语句动态创建表和列

目的

为了动态从数据库中生成表以及定义属性

步骤

创建新的xml文件以及mapper接口类

TabelControllerMapper.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.me.mapper.TableControllerMapper">  


	<update id="createNewTable">  
		CREATE TABLE ${myMap.theTableName}(  
			id int(10) PRIMARY KEY AUTO_INCREMENT NOT NULL  
			<foreach collection="myMap" index="key" item="value">  
				<if test="key.toString() != 'theTableName'.toString()">  
					,${key} ${value}  
				</if>  
			</foreach>  );  
	</update>  
</mapper>

注意第一句定义id后面不加逗号,在foreach循环里前面加上逗号是为了语句最后一次执行后面没有逗号,否则会报错


TableControllerMapper接口

package com.me.mapper;  

import org.apache.ibatis.annotations.Mapper;  
import org.apache.ibatis.annotations.Param;  

import java.util.HashMap;  

/**  
 * @author fenghere  
 */@Mapper  
	public interface TableControllerMapper {  
    /**  
     * fetch data by rule id * * @param map mymap  
     * @return Result<XxxxDO>  
     */  

  void createNewTable(@Param(value = "myMap") HashMap map);  
}

输入的参数为hashmap类型,关于这种引入参数的方法另一篇博客有写

http://xfff.xyz/2019/01/07/Mybatis%E4%BC%A0%E5%8F%82%E6%96%B9%E6%B3%95/


测试

写一个测试类

package com.me.demo;  

import com.me.beans.User;  
import com.me.mapper.TableControllerMapper;  
import com.me.mapper.UserMapper;  
import com.me.security.Md5Utils;  
import com.me.service.UserService;  
import org.junit.Test;  
import org.springframework.beans.factory.annotation.Autowired;  

import java.io.UnsupportedEncodingException;  
import java.security.NoSuchAlgorithmException;  
import java.util.HashMap;  

/**  
 * @ClassName MyTest  
 * @Description TODO  
 * @Author xufeng  
 * @Data 2019/2/22 13:46  
 * @Version 1.0  
 **/
 public class MyTest extends DemoApplicationTests{  


  @Autowired  
  TableControllerMapper tableControllerMapper;  

  @Test  
  public void myTest(){  
          HashMap<String,String> mymap = new HashMap<>();  
          mymap.put("theTableName","dsafakshfdksahlfhdashdfh");  
          mymap.put("text","text");  
          mymap.put("username","varchar(10)");  
          mymap.put("ididiid","int");  
          tableControllerMapper.createNewTable(mymap);  

  }  
}

MyTest类继承DemoApplicationTests是为了引入springboot项目的数据库和mapper配置

执行完成,进入数据库查看

如下

在这里插入图片描述
在这里插入图片描述


另外,删除表等操作应为类似的操作.

<select id="existTable" parameterType="java.lang.String" resultType="java.lang.Integer">
    select count(*)
    from information_schema.TABLES
    where LCASE(table_name) = #{tableName}
</select>


<update id="dropTable">
    DROP TABLE ${tablename}
</update>
  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值