解決spring data jpa 批量保存更新的問題
使用jpa批量保存時,看日志發(fā)現(xiàn)是一條一條打印的,然后去看了下源碼,果然是循環(huán)調(diào)用的單個保存(巨坑啊)
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根據(jù)自己的數(shù)據(jù)庫情況來設(shè)置
配置好后,感覺終于可以批量保存了,立馬試了一把,結(jié)果,一首涼涼。。。(并沒什么用)
繼續(xù)查資料,終于發(fā)現(xiàn)了還有一個坑,那就是jpa中主鍵策略會影響批量功能!!
如果主鍵策略使用了IDENTITY 也就是@GeneratedValue(strategy = GenerationType.IDENTITY),那么批量功能不支持的,
如果要開啟批量,那么就要使用sequence策略,也就是@GeneratedValue(strategy = GenerationType.SEQUENCE),
然后立馬去開啟,結(jié)果發(fā)現(xiàn)再次入坑,原來mysql數(shù)據(jù)庫是無法使用sequence策略的,已淚奔。。。。。
批量功能只能自己去單獨(dú)找尋方法實(shí)現(xiàn)了。
jpa在批量添加的時候,存儲慢如何解決問題spring.datasource.url = jdbc:mysql://xxxxxxxx:xxxx/xxxxx?useSSL=false&useUnicode=true&characterEncoding=utf-8&rewriteBatchedStatements=true&autoReconnect=true
入口下加
@EnableTransactionManagement@SpringBootApplication@EnableTransactionManagement
service實(shí)現(xiàn)類下加
@Service@Transactional自己的字段多少來寫格式不能變下面是一個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導(dǎo)入這個直接用,調(diào)用這個方法createBatch();
開啟數(shù)據(jù)空批量配置:
rewriteBatchedStatements=true
開啟事務(wù):
@EnableTransactionManagement ,@Transactional
可以一試。以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP實(shí)現(xiàn)加法驗(yàn)證碼2. CSS可以做的幾個令你嘆為觀止的實(shí)例分享3. PHP循環(huán)與分支知識點(diǎn)梳理4. Spring注入Date類型的三種方法總結(jié)5. ASP基礎(chǔ)知識Command對象講解6. PHP session反序列化漏洞超詳細(xì)講解7. ASP基礎(chǔ)入門第二篇(ASP基礎(chǔ)知識)8. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)9. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享10. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))
