項目中業(yè)務(wù)需求的不同,有時候我們需要動態(tài)操作數(shù)據(jù)表(如:動態(tài)建表、操作表字段等)。常見的我們會把日志、設(shè)備實時位置信息等存入數(shù)據(jù)表,并且以一定時間段生成一個表來存儲,log_201806、log_201807等。在這里我們用MyBatis實現(xiàn),會用到動態(tài)SQL。
動態(tài)SQL是Mybatis的強大特性之一,MyBatis在對sql語句進行預(yù)編譯之前,會對sql進行動態(tài)解析,解析為一個BoundSql對象,也是在此對動態(tài)sql進行處理。
在動態(tài)sql解析過程中,#{ }與${ }的效果是不一樣的:
#{ } 解析為一個JDBC預(yù)編譯語句(prepared statement)的參數(shù)標(biāo)記符。
如以下sql語句:
select * from user where name = #{name};
會被解析為:
select * from user where name = ?;
可以看到#{ }被解析為一個參數(shù)占位符 ? 。
${ } 僅僅為一個純粹的String替換,在動態(tài)SQL解析階段將會進行變量替換。
如以下sql語句:
select * from user where name = ${name};
當(dāng)我們傳遞參數(shù)“joanna”時,sql會解析為:
select * from user where name = “joanna”;
可以看到預(yù)編譯之前的sql語句已經(jīng)不包含變量name了。
綜上所述,${ }的變量的替換階段是在動態(tài)SQL解析階段,而#{ } 的變量的替換是在DBMS中。
下面實現(xiàn)MyBatis動態(tài)創(chuàng)建表,判斷表是否存在,刪除表功能。
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);}
總結(jié)
以上所述是小編給大家介紹的MyBatis動態(tài)創(chuàng)建表的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對VeVb武林網(wǎng)網(wǎng)站的支持!
|
新聞熱點
疑難解答
圖片精選