Mybatis進行動態sql操作
阿新 • • 發佈:2018-12-29
使用mybatis進行動態sql操作其實有兩種:1.用script標籤包圍,然後像xml語法一樣書寫。2.用Provider去實現SQL拼接,下面分別介紹這兩種方法的使用。
1.用script標籤包圍
這種方法使用起來很簡單,可以使用if when foreach等元素,它支援的元素有:
trim
where
set
foreach
if
choose
when
otherwise
bind
列舉兩個例子,經常使用到的when與foreach
when:
其中test表示式中如果為true,才會將and type = #{type}語句拼接進去
@Select("<script> " + "SELECT * from t_sys_smart_device where 1 = 1 \n" + "<when test='type != null'> " + "and type = #{type}\n" + "</when>" + "and deleted_at is null" + "</script>") List<SmartDeviceEntity> queryDevicesByType(@Param("type") Integer type);
foreach
collection:可用通過@Param註解指定引數名,引數List
item:引數呼叫名稱,引數List的單個值
open:在迴圈前新增字首
close:在迴圈後新增字尾
index:索引、下標
separator:分隔符,每次迴圈完成後新增此分隔符
@Select("<script>" + "SELECT * FROM t_sys_account" "where union_id in" "<foreach item='unionId' index='index' collection='unionIds' open='(' separator=',' close=')'>" + "#{unionId}" + "</foreach>" + "AND user.deleted_at IS NULL" + "</script>") List<String> queryUsers(@Param("unionIds") List<String> unionIds);
2.用Provider去實現SQL拼接
MyBatis提供了多個註解如:@InsertProvider,@UpdateProvider,@DeleteProvider和@SelectProvider,這個註解都可以建立動態sql。
主要用到的兩個屬性:
type:指定所在的類
method:指定類所在的方法
舉一個例子,動態插入資料,其插入的欄位是動態的。
/**第一list段是所插元素的欄位名,第二個list是所插入資料的集合*/ @InsertProvider( type = SalaryProvider.class,method = "insertSalary") void insertData(List<String> headers, List<String> datas);
/**
* Created by XiChuan on 2018-12-25.
*/
public class SalaryProvider {
/**動態插入sql*/
/**使用<script>不可以的原因,在欄位上會有'wage1' 存在,會報錯*/
public String insertSalary(List<String> headers,List<String> datas){
StringBuilder sql = new StringBuilder();
sql.append("insert into t_pub_salary_temp(");
//插入欄位
headers.stream().forEach(header -> sql.append(header+","));
sql.deleteCharAt(sql.length()-1); //將最後一個','去掉
sql.append(") values(");
//插入資料
datas.stream().forEach(data -> sql.append("'"+data+"',"));
sql.deleteCharAt(sql.length()-1); //將最後一個','去掉
sql.append(");");
String insertSql = sql.toString();
System.out.println("sql:"+insertSql);
return insertSql; //返回sql
}
}