转载请注明出处:http://www.javashuo.com/article/p-ukskkogo-w.html html
项目中业务需求的不一样,有时候咱们须要动态操做数据表(如:动态建表、操做表字段等)。常见的咱们会把日志、设备实时位置信息等存入数据表,而且以必定时间段生成一个表来存储,log_20180六、log_201807等。在这里咱们用MyBatis实现,会用到动态SQL。java
动态SQL是Mybatis的强大特性之一,MyBatis在对sql语句进行预编译以前,会对sql进行动态解析,解析为一个BoundSql对象,也是在此对动态sql进行处理。sql
在动态sql解析过程当中,#{ }与${ }的效果是不同的:apache
#{ } 解析为一个JDBC预编译语句(prepared statement)的参数标记符。 如如下sql语句: select * from user where name = #{name}; 会被解析为: select * from user where name = ?;
能够看到#{ }被解析为一个参数占位符 ? 。微信
${ } 仅仅为一个纯粹的String替换,在动态SQL解析阶段将会进行变量替换。 如如下sql语句: select * from user where name = ${name};
当咱们传递参数“joanna”时,sql会解析为: select * from user where name = “joanna”;
能够看到预编译以前的sql语句已经不包含变量name了。mybatis
综上所述,${ }的变量的替换阶段是在动态SQL解析阶段,而#{ } 的变量的替换是在DBMS中。app
下面实现MyBatis动态建立表,判断表是否存在,删除表功能。spa
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="xx.xxx.xx.mapper.OperateTableMapper" > <select id="existTable" parameterType="String" resultType="Integer"> select count(*) from information_schema.TABLES where LCASE(table_name)=#{tableName} </select> <update id="dropTable"> DROP TABLE IF EXISTS ${tableName} </update> <update id="createNewTable" parameterType="String"> CREATE TABLE ${tableName} ( id bigint(20) NOT NULL AUTO_INCREMENT, entityId bigint(20) NOT NULL, dx double NOT NULL, dy double NOT NULL, dz double NOT NULL, ntype varchar(32) NOT NULL, gnssTime bigint(20) NOT NULL, speed float DEFAULT NULL, direction float DEFAULT NULL, attributes varchar(255) DEFAULT NULL, PRIMARY KEY (id)) </update> <insert id="insert" parameterType="xx.xxx.xx.po.Trackpoint"> insert into ${tableName} (entityId,dx,dy,dz,ntype,gnssTime,speed,direction,attributes) values (#{trackpoint.entityid}, #{trackpoint.dx}, #{trackpoint.dy}, #{trackpoint.dz}, #{trackpoint.ntype}, #{trackpoint.gnsstime}, #{trackpoint.speed}, #{trackpoint.direction}, #{trackpoint.attributes}) </insert> </mapper>
Mapper.javacode
package xx.xxx.xx.mapper; import org.apache.ibatis.annotations.Param; import xx.xxx.xx.po.Trackpoint; public interface OperateTableMapper { int existTable(String tableName); int dropTable(@Param("tableName")String tableName); int createNewTable(@Param("tableName")String tableName); int insert(@Param("tableName")String tableName,@Param("trackpoint")Trackpoint trackpoint); }
若是此文对您有帮助,微信打赏我一下吧~