MyBatis动态SQL,MyBatis动态(创建数据库表、修改数据、插入数据)
写这个的初衷是为了记录最近开发新项目而遇到的问题,记录下来,方便后续再有类似的功能点,同时给广大开发者提供一些思路!!
1.动态创建数据库表
传入的对象:
//map是传入sql的对象,list是需要动态生成的字段列名称
Map<String, Object> map = new HashMap<>();
List<String> list = new ArrayList<>();
map.put("tablecode",“自定义表名称”);
map.put("tableParams",list);
Mybatis层:
//切记:语句创建结束不要添加“;”,否则会出现错误
//需要注意:foreach对应的collection对象一定要在传入的参数里面
<update id="createTable" parameterType="java.util.Map" >
CREATE TABLE ${tablecode}(
ID number not null ,
CODEID number ,
<foreach collection="tableParams" item="item" index="index" >
${item} VARCHAR(255),
</foreach>
primary key (ID)
)
</update>
2.通用的表数据插入,可根据传入不同的表命插入不同的数据传入的对象:
//map是传入sql的对象,list1是需要动态生成的字段列名称,list2是需要动态生成的字段列对应的值
Map<String, Object> map = new HashMap<>();
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
map.put("tablecode",“自定义表名称”);
map.put("tableParams",list1);
map.put("tableParamsValue",list2);
Mybatis层:
//需要注意:foreach对应的collection对象一定要在传入的参数里面
<insert id="insertTable" parameterType="java.util.Map">
insert into ${tablecode}
<foreach collection="tableParams" item="column" open="(" separator="," close=")">
${column}
</foreach>
values
<foreach collection="tableParamsValue" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</insert>
3.通用的修改表数据,可根据传入不同的表命修改不同的数据,也可以根据传入的列值进行定向修改:
//map是传入sql的对象,tableMap是需要存储的k:v键值对
Map<String, Object> map = new HashMap<>();
Map<String, String> tableMap= new HashMap<>();
map.put("tablecode",“自定义表名称”);
map.put("tableMap",tableMap);
Mybatis层:
//需要注意:foreach对应的collection对象一定要在传入的参数里面
<update id="updateCodeTable" parameterType="java.util.Map">
update ${tablecode} set
<foreach collection="tableMap.entrySet()" index="key" item="value" open="" separator="," close="">
${key} = #{value}
</foreach>
where ID=#{id}
</update>
4.删除对应表的数据:
//map是传入sql的对象,tableMap是需要存储的k:v键值对
Map<String, Object> map = new HashMap<>();
map.put("tablecode",“自定义表名称”);
map.put("id","传入的需要删除的ID”);
Mybatis层:
//需要注意:foreach对应的collection对象一定要在传入的参数里面
<delete id="deleteTable" parameterType="java.util.Map">
delete from ${tablecode} where id = #{id}
</delete>
5.查询对应表的数据:
Mybatis层:
//需要注意:foreach对应的collection对象一定要在传入的参数里面
<select id="selectTable" parameterType="java.util.Map" resultType="java.util.Map">
select * from ${tablecode}
</select>
6.询动态表的所有列名
Mybatis层:
<select id="selectColumnnameByCond" parameterType="java.util.Map" resultType="java.lang.String">
select column_name from user_tab_columns where table_name = '${tablecode}'
</select>
后续会更新mysql版本,谢谢大家观看!!