您的位置:首頁技術文章
文章詳情頁

解決spring data jpa 批量保存更新的問題

瀏覽:24日期:2023-07-11 14:59:20
spring data jpa 批量保存更新問題

使用jpa批量保存時,看日志發現是一條一條打印的,然后去看了下源碼,果然是循環調用的單個保存(巨坑啊)

解決spring data jpa 批量保存更新的問題

經查詢jpa是可以實現批量保存更新的,具體設置如下:

spring.jpa.properties.hibernate.jdbc.batch_size=500spring.jpa.properties.hibernate.jdbc.batch_versioned_data=truespring.jpa.properties.hibernate.order_inserts=truespring.jpa.properties.hibernate.order_updates =true其中:batch_size根據自己的數據庫情況來設置

配置好后,感覺終于可以批量保存了,立馬試了一把,結果,一首涼涼。。。(并沒什么用)

繼續查資料,終于發現了還有一個坑,那就是jpa中主鍵策略會影響批量功能?。?/p>

如果主鍵策略使用了IDENTITY 也就是@GeneratedValue(strategy = GenerationType.IDENTITY),那么批量功能不支持的,

如果要開啟批量,那么就要使用sequence策略,也就是@GeneratedValue(strategy = GenerationType.SEQUENCE),

然后立馬去開啟,結果發現再次入坑,原來mysql數據庫是無法使用sequence策略的,已淚奔。。。。。

批量功能只能自己去單獨找尋方法實現了。

jpa在批量添加的時候,存儲慢如何解決問題

spring.datasource.url = jdbc:mysql://xxxxxxxx:xxxx/xxxxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true

解決spring data jpa 批量保存更新的問題

入口下加

@EnableTransactionManagement@SpringBootApplication@EnableTransactionManagement

service實現類下加

@Service@Transactional![在這里插入圖片描述](https://img-blog.csdnimg.cn/20191220111053531.png引用@Autowiredprivate NamedParameterJdbcTemplate namedParameterJdbcTempla

解決spring data jpa 批量保存更新的問題

sql語句這樣寫:根據自己的字段多少來寫格式不能變下面是一個demo

String sql = “INSERT INTO xxxx(id,name,age) VALUES (:id,:name,:age)”;List uparChnMulMinList = (List) map.get(“uparChnMulMinList”);SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(uparChnMulMinList.toArray());namedParameterJdbcTemplate.batchUpdate(sql, batch);

自定義的list:List

SqlParameterSourceUtils導入這個直接用,調用這個方法createBatch();

開啟數據空批量配置:

rewriteBatchedStatements=true

開啟事務:

@EnableTransactionManagement ,@Transactional

可以一試。以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Spring
相關文章:
国产综合久久一区二区三区