項目中業務需求的不同,有時候我們需要動態操作數據表(如:動態建表、操作表字段等)。常見的我們會把日志、設備實時位置信息等存入數據表,并且以一定時間段生成一個表來存儲,log_201806、log_201807等。在這里我們用mybatis實現,會用到動態sql。
動態sql是mybatis的強大特性之一,mybatis在對sql語句進行預編譯之前,會對sql進行動態解析,解析為一個boundsql對象,也是在此對動態sql進行處理。
在動態sql解析過程中,#{ }與${ }的效果是不一樣的:
#{ } 解析為一個jdbc預編譯語句(prepared statement)的參數標記符。
如以下sql語句:
1
|
select * from user where name = #{name}; |
會被解析為:
1
|
select * from user where name = ?; |
可以看到#{ }被解析為一個參數占位符 ? 。
${ } 僅僅為一個純粹的string替換,在動態sql解析階段將會進行變量替換。
如以下sql語句:
1
|
select * from user where name = ${name}; |
當我們傳遞參數“joanna”時,sql會解析為:
1
|
select * from user where name = “joanna”; |
可以看到預編譯之前的sql語句已經不包含變量name了。
綜上所述,${ }的變量的替換階段是在動態sql解析階段,而#{ } 的變量的替換是在dbms中。
下面實現mybatis動態創建表,判斷表是否存在,刪除表功能。
mapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
<?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;
1
2
3
4
5
6
7
8
|
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); } |
總結
以上所述是小編給大家介紹的mybatis動態創建表的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/Joanna-Yan/p/9187538.html