原来使用sql时也都只是DML(Data Manipulation Language 数据操控语言)的,对于DDL(Data Definition Language 数据定义语言)的操作比较少涉及,最近项目中恰巧需要进行DDL操作,进行简单的记录。项目需求,根据前台传来的表名,字段,数据,进行动态的创建表格,实现对表格的增删改查操作。
首先创建一个实体类,用来封装操作表的数据。
/**
*
* @Description :动态操作表变量
* @author Bush罗
* @date 2018年7月19日
*
*/
public class OperateTable {
//表名
private String tableName;
//用于添加字段使用
private String wordSegment;
//用于创建数据库时使用,存放所有需要的字段
private List<String> listWord;
//字段所表示的中文意思,需要从前台传过来
private List<String> listWordMean;
//用于删除数据使用的id
private Integer id;
//表示一行数据,用户填写的一行数据
private List<String> listData;
//返回该数据库的所有表明
private List<String> listTableName;
//存放字段和数据
private Map<String,String> mapWordData;
dao层接口
public interface OperateTableService {
// 创建表
void createTable(OperateTable operateTable);
// 插入数据
void insertTable(OperateTable operateTable);
// 查找所有表名
List<TableName> findAllTableName();
// 更新数据库
void updateTable(@Param("content") Map<String, String> mapWordData);
// 更新数据库
void updateTable1(OperateTable operateTable);
// 动态删除数据
void deleteById(OperateTable operateTable);
// 动态为表添加字段
void addColumn(OperateTable operateTable);
}
最重要的动态sql语句,也是mybatis最大的优点,灵活
<?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.smxy.lq.dao.OperateTableMapper">
<!--创建一个以id为主键的自增表 -->
<!-- 1.ddl使用update标签 -->
<!-- 2.ddl使用${}取值 -->
<!-- 3.动态列实际上只是普通的foreach, 常见问题是使用#{}取值造成语法错误 -->
<update id="createTable" parameterType="com.smxy.lq.pojo.OperateTable">
create table ${tableName} (
id int(100) NOT NULL PRIMARY KEY
AUTO_INCREMENT,
<foreach collection="listWord" item="word" separator=",">
${word}
varchar(255)
</foreach>
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</update>
<insert id="insertTable" parameterType="com.smxy.office.pojo.OperateTable">
<!-- 将插入数据的主键返回,返回到对象中 SELECT LAST_INSERT_ID():得到刚insert进去记录的主键值,只适用与自增主键
keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性 order:SELECT LAST_INSERT_ID()执行顺序,相对于insert语句来说它的执行顺序
resultType:指定SELECT LAST_INSERT_ID()的结果类型 -->
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
SELECT
LAST_INSERT_ID()
</selectKey>
insert into
${tableName}
<trim prefix="(" suffix=")" suffixOverrides=",">
<foreach collection="mapWordData.keys" item="key" open=""
close="" separator=",">
${key}
</foreach>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<foreach collection="mapWordData.values" item="value"
separator=",">
#{value}
</foreach>
</trim>
</insert>
<!--查找所有数据库的表的名字 -->
<select id="findAllTableName" resultType="com.smxy.lq.pojo.TableName">
select
table_name
FROM
information_schema.tables
WHERE table_schema = 'market'
AND table_type =
'base table'
AND TABLE_NAME LIKE "office_%"
</select>
<!--动态更新数据库 -->
<update id="updateTable" parameterType="java.util.Map">
update office_1 SET
<foreach collection="content.keys" item="key" open="" close=""
separator=",">
${key} = #{content[${key}]}
</foreach>
where id = 1
</update>
<!-- 动态更新数据库 -->
<update id="updateTable1" parameterType="com.smxy.office.pojo.OperateTable">
update ${tableName}
<set>
<foreach item="value" index="key" collection="mapWordData.entrySet()"
open="" close="" separator=",">
${key}=#{value}
</foreach>
</set>
where id = #{id}
</update>
<!--动态删除数据 -->
<delete id="deleteById" parameterType="com.smxy.lq.pojo.OperateTable">
delete from ${tableName}
where id = #{id}
</delete>
<!--动态为表增加字段 -->
<update id="addColumn" parameterType="com.smxy.lq.pojo.OperateTable">
alter table ${tableName} add column ${wordSegment} varchar(255);
</update>
</mapper>
Controller测试用例
/**
*
* @Description :动态操作数据库案例
* @author Bush罗
* @date 2018年7月20日
*
*/
@Controller
public class OperateTableController {
@Autowired
private OperateTableService operateTableService;
@ResponseBody
@RequestMapping("/creat")
public String creat() {
System.out.println("创建");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
List<String> list = new LinkedList<String>();
list.add("of_1");
list.add("of_2");
list.add("of_3");
operateTable.setListWord(list);
operateTableService.createTable(operateTable);
return "创建成功";
}
@ResponseBody
@RequestMapping("/insertTable")
public String insertTable() {
System.out.println("插入");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
Map<String,String> mapWordData=new HashMap<String,String>();
mapWordData.put("username", "小红");
mapWordData.put("sex", "男");
mapWordData.put("phonenumber", "123456789");
mapWordData.put("teacherid", "500");
operateTable.setMapWordData(mapWordData);
operateTableService.insertTable(operateTable);
return "success";
}
@ResponseBody
@RequestMapping("/updateTable")
public String updateTable() {
System.out.println("更新");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
Map<String,String> mapWordData=new HashMap<String,String>();
mapWordData.put("of_1", "小红");
mapWordData.put("of_2", "明");
mapWordData.put("of_3", "500");
operateTable.setMapWordData(mapWordData);
System.out.println(operateTable.toString());
operateTableService.updateTable(mapWordData);
return "更新成功";
}
@ResponseBody
@RequestMapping("/updateTable1")
public String updateTable1() {
System.out.println("更新1");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
Map<String,String> mapWordData=new HashMap<String,String>();
mapWordData.put("of_1", "6红");
mapWordData.put("of_2", null);
mapWordData.put("of_3", "小芳");
operateTable.setMapWordData(mapWordData);
operateTable.setId(3);
operateTableService.updateTable1(operateTable);
return "更新成功1";
}
@ResponseBody
@RequestMapping("delete")
public String delete(){
System.out.println("删除");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
operateTable.setId(3);
operateTableService.deleteById(operateTable);
return "删除成功";
}
@ResponseBody
@RequestMapping("addcolumn")
public String addcolumn(){
System.out.println("添加字段");
OperateTable operateTable = new OperateTable();
operateTable.setTableName("office_1");
operateTable.setWordSegment("of_4");
operateTableService.deleteById(operateTable);
return "添加成功";
}
}