1. 程式人生 > 其它 >mybatis使用foreach標籤和oracle merge into 語法實現批量更新

mybatis使用foreach標籤和oracle merge into 語法實現批量更新

1.使用foreach標籤和oracle merge into 語法需要在該標籤增加 separator=";" open="BEGIN" close=";END;" 三個屬性,寫法不當會報錯,例如:

PLS-00103: 出現符號 "end-of-file"在需要下列之一時:
(
begin case declare end exception exit for goto if loop mod
null pragma raise return select update while with
<an identifier> <a double-quoted delimited-identifier>
<a bind variable> << continue close current delete fetch lock
insert open rollback savepoint set sql execute commit forall
merge pipe purge json_exists json_value json_query
json_object json_array
2.USING ON子句,ON條件的欄位不能更新,若更新會報錯,例如:

無法更新 ON 子句中引用的列: "T"."IDT_ID"
3.UPDATE SET 子句中更新欄位可以使用case when ... then ... end語句

寫法不當會報錯,例如:

Caused by: com.alibaba.druid.sql.parser.ParserException:
syntax error, expect RPAREN, actual RBRACE pos 913, line 36, column 98, token RBRACE
4.如果mybatis和druid資料庫連線池共用,需要配置WallFilter、WallConfig 兩個javabean,該bean的作用是允許mybatis的一個sql標籤可以執行多條sql語句,若果不配置會報錯:

Caused by: java.sqlSQLException: sql injection violation, multi-statement not allow :

若使用spring需要在spring的xml配置檔案裡配置兩個bean:WallFilter 和 WallConfig,使用springboot則參考以下程式碼:程式碼例項:

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;


@Configuration
public class DruidConfig {

//使用連線池dataSource
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
List<Filter> filterList = new ArrayList<>();
filterList.add(wallFilter());
druidDataSource.setProxyFilters(filterList);
return druidDataSource;

}

@Bean
public WallFilter wallFilter() {
WallFilter wallFilter = new WallFilter();
wallFilter.setConfig(wallConfig());
return wallFilter;
}

@Bean
public WallConfig wallConfig() {
WallConfig config = new WallConfig();
config.setMultiStatementAllow(true);//允許一次執行多條語句
config.setNoneBaseStatementAllow(true);//允許非基本語句的其他語句
return config;
}
}
5.最後看下完整的更新sql僅供參考:

<update id="upd" parameterType="map">
<foreach collection="LIST" item="item" separator=";" open="BEGIN" close=";END;" index="index">
MERGE INTO T_PERSON T
USING (SELECT #{item.IDT_ID} IDT_ID FROM dual) T2
ON (T.IDT_ID = T2.IDT_ID)
WHEN NOT MATCHED THEN
INSERT
(...)
VALUES
(...)
WHEN MATCHED THEN
UPDATE
SET ... = ...,
PERSON_TYPE = CASE WHEN (PERSON_ID =#{item.PERSON_ID} AND PERSON_TYPE ='1') THEN '1' ELSE '0' END
</foreach>
</update>
————————————————
版權宣告:本文為CSDN博主「易大師不易」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/jinziweiwang/article/details/122457305