MyBatis動態創建表


  轉載請注明出處: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);
}
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM