解決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中主鍵策略會影響批量功能!!
如果主鍵策略使用了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
入口下加
@EnableTransactionManagement@SpringBootApplication@EnableTransactionManagement
service實現類下加
@Service@Transactional 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
可以一試。以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: