如何使用Hibernate批处理DELETE语句
介紹
在我以前的文章中 ,我解釋了批處理INSERT和UPDATE語句所需的Hibernate配置。 這篇文章將繼續(xù)本主題的DELETE語句批處理。
領(lǐng)域模型實(shí)體
 我們將從以下實(shí)體模型開始: 
 
Post實(shí)體與Comment具有一對多關(guān)聯(lián),并且與PostDetails實(shí)體具有一對一關(guān)系:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post",orphanRemoval = true) private List<Comment> comments = new ArrayList<>();@OneToOne(cascade = CascadeType.ALL, mappedBy = "post",orphanRemoval = true, fetch = FetchType.LAZY) private PostDetails details;即將進(jìn)行的測試將針對以下數(shù)據(jù)進(jìn)行:
doInTransaction(session -> {int batchSize = batchSize();for(int i = 0; i < itemsCount(); i++) {int j = 0;Post post = new Post(String.format("Post no. %d", i)); post.addComment(new Comment( String.format("Post comment %d:%d", i, j++)));post.addComment(new Comment(String.format("Post comment %d:%d", i, j++)));post.addDetails(new PostDetails());session.persist(post);if(i % batchSize == 0 && i > 0) {session.flush();session.clear();}} });休眠配置
正如已經(jīng)說明 ,以下屬性所需的配料INSERT和UPDATE語句:
properties.put("hibernate.jdbc.batch_size", String.valueOf(batchSize())); properties.put("hibernate.order_inserts", "true"); properties.put("hibernate.order_updates", "true"); properties.put("hibernate.jdbc.batch_versioned_data", "true");接下來,我們將檢查DELETE語句是否也被批處理。
JPA級(jí)聯(lián)刪除
因?yàn)榧?jí)聯(lián)實(shí)體狀態(tài)轉(zhuǎn)換很方便,所以我將證明CascadeType.DELETE和JDBC批處理不能很好地混合使用。
以下測試將要進(jìn)行:
- 選擇一些帖子以及評論和帖子 詳細(xì)信息
- 刪除帖子 ,同時(shí)將delete事件傳播到Comments和PostDetails
運(yùn)行此測試將給出以下輸出:
Query:{[delete from Comment where id=? and version=?][55,0]} {[delete from Comment where id=? and version=?][56,0]} Query:{[delete from PostDetails where id=?][3]} Query:{[delete from Post where id=? and version=?][3,0]} Query:{[delete from Comment where id=? and version=?][54,0]} {[delete from Comment where id=? and version=?][53,0]} Query:{[delete from PostDetails where id=?][2]} Query:{[delete from Post where id=? and version=?][2,0]} Query:{[delete from Comment where id=? and version=?][52,0]} {[delete from Comment where id=? and version=?][51,0]} Query:{[delete from PostDetails where id=?][1]} Query:{[delete from Post where id=? and version=?][1,0]}僅批注Comment DELETE語句,其他實(shí)體在單獨(dú)的數(shù)據(jù)庫往返中刪除。
此行為的原因由ActionQueue排序?qū)崿F(xiàn)給出:
if ( session.getFactory().getSettings().isOrderUpdatesEnabled() ) {// sort the updates by pkupdates.sort(); } if ( session.getFactory().getSettings().isOrderInsertsEnabled() ) {insertions.sort(); }雖然介紹了INSERTS和UPDATES ,但根本不對DELETE語句進(jìn)行排序。 僅當(dāng)所有語句都屬于同一數(shù)據(jù)庫表時(shí),才能重新使用JDBC批處理。 當(dāng)傳入語句針對另一個(gè)數(shù)據(jù)庫表時(shí),必須釋放當(dāng)前批處理,以便新批處理與當(dāng)前語句數(shù)據(jù)庫表匹配:
public Batch getBatch(BatchKey key) {if ( currentBatch != null ) {if ( currentBatch.getKey().equals( key ) ) {return currentBatch;}else {currentBatch.execute();currentBatch.release();}}currentBatch = batchBuilder().buildBatch(key, this);return currentBatch; }移除孤兒和手動(dòng)沖洗
一種變通方法是在前進(jìn)到新的Child關(guān)聯(lián)之前,先手動(dòng)刷新Hibernate Session,然后解除所有Child實(shí)體的關(guān)聯(lián):
@Test public void testOrphanRemoval() {LOGGER.info("Test batch delete with orphan removal");final AtomicReference<Long> startNanos = new AtomicReference<>();addDeleteBatchingRows();doInTransaction(session -> {List<Post> posts = session.createQuery("select distinct p " +"from Post p " +"join fetch p.details d " +"join fetch p.comments c").list();startNanos.set(System.nanoTime());posts.forEach(Post::removeDetails);session.flush();posts.forEach(post -> {for (Iterator<Comment> commentIterator = post.getComments().iterator(); commentIterator.hasNext(); ) {Comment comment = commentIterator.next();comment.post = null;commentIterator.remove();}});session.flush();posts.forEach(session::delete);});LOGGER.info("{}.testOrphanRemoval took {} millis",getClass().getSimpleName(),TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos.get())); }這次,所有DELETE語句均已正確批處理:
Query:{[delete from PostDetails where id=?][2]} {[delete from PostDetails where id=?][3]} {[delete from PostDetails where id=?][1]} Query:{[delete from Comment where id=? and version=?][53,0]} {[delete from Comment where id=? and version=?][54,0]} {[delete from Comment where id=? and version=?][56,0]} {[delete from Comment where id=? and version=?][55,0]} {[delete from Comment where id=? and version=?][52,0]} {[delete from Comment where id=? and version=?][51, Query:{[delete from Post where id=? and version=?][2,0]} {[delete from Post where id=? and version=?][3,0]} {[delete from Post where id=? and version=?][1,0]}SQL級(jí)聯(lián)刪除
更好的解決方案是使用SQL級(jí)聯(lián)刪除,而不是JPA實(shí)體狀態(tài)傳播機(jī)制。 這樣,我們還可以減少DML語句的數(shù)量。 由于Hibernate Session充當(dāng)事務(wù)后寫式緩存 ,因此在將實(shí)體狀態(tài)轉(zhuǎn)換與數(shù)據(jù)庫端自動(dòng)操作混合使用時(shí),我們必須格外謹(jǐn)慎,因?yàn)槌志眯陨舷挛目赡軣o法反映最新的數(shù)據(jù)庫更改。
Post實(shí)體一對多 注釋關(guān)聯(lián)使用Hibernate特定的@OnDelete批注進(jìn)行標(biāo)記,以便自動(dòng)生成的數(shù)據(jù)庫模式包括ON DELETE CASCADE指令:
@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "post") @OnDelete(action = OnDeleteAction.CASCADE) private List<Comment> comments = new ArrayList<>();生成以下DDL :
alter table Comment add constraint FK_apirq8ka64iidc18f3k6x5tc5 foreign key (post_id) references Post on delete cascade使用PostDetails實(shí)體一對一的Post關(guān)聯(lián)也可以做到這一點(diǎn) :
@OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id") @MapsId @OnDelete(action = OnDeleteAction.CASCADE) private Post post;以及相關(guān)的DDL :
alter table PostDetails add constraint FK_h14un5v94coafqonc6medfpv8 foreign key (id) references Post on delete cascadeCascadeType.ALL和orphanRemoval替換為CascadeType.PERSIST和CascadeType.MERGE ,因?yàn)槲覀儾辉傧M鸋ibernate傳播實(shí)體刪除事件。
測試僅刪除Post實(shí)體。
doInTransaction(session -> {List<Post> posts = session.createQuery("select p from Post p").list();startNanos.set(System.nanoTime());for (Post post : posts) {session.delete(post);} });由于只有一個(gè)目標(biāo)表,因此DELETE語句已正確批處理。
Query:{[delete from Post where id=? and version=?][1,0]} {[delete from Post where id=? and version=?][2,0]} {[delete from Post where id=? and version=?][3,0]}結(jié)論
如果INSERT和UPDATE語句的批處理只是配置問題,則DELETE語句需要一些其他步驟,這可能會(huì)增加數(shù)據(jù)訪問層的復(fù)雜性。
- 代碼可在GitHub上獲得 。
翻譯自: https://www.javacodegeeks.com/2015/03/how-to-batch-delete-statements-with-hibernate.html
總結(jié)
以上是生活随笔為你收集整理的如何使用Hibernate批处理DELETE语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 拍卖公司备案申请(拍卖公司备案)
- 下一篇: (linux tar文件)
