转载请注明出处:https://www.cnblogs.com/Joanna-Yan/p/9187538.html

  项目中业务需求的不同,有时候我们需要动态操作数据表(如:动态建表、操作表字段等)。常见的我们会把日志、设备实时位置信息等存入数据表,并且以一定时间段生成一个表来存储,log_201806、log_201807等。在这里我们用MyBatis实现,会用到动态SQL。
  动态SQL是Mybatis的强大特性之一,MyBatis在对sql语句进行预编译之前,会对sql进行动态解析,解析为一个BoundSql对象,也是在此对动态sql进行处理。  在动态sql解析过程中,#{ }与${ }的效果是不一样的:

#{ } 解析为一个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了。
  综上所述,${ }的变量的替换阶段是在动态SQL解析阶段,而#{ } 的变量的替换是在DBMS中。
  下面实现MyBatis动态创建表,判断表是否存在,删除表功能。

  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.java

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);
}

如果此文对您有帮助,微信打赏我一下吧~

图片描述