簡體   English   中英

Hibernate @OneToMany刪除並再次插入

[英]Hibernate @OneToMany delete and inser again

我在使用Hibernate 3.6.10.Final時遇到問題。

我有一個使用以下內容映射的OneToMany關系:

public class Master implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY) 
    Long masterId;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "master")
    private List<Row> rows = new ArrayList<Attribute>(0);

    // Getter and setters and other properties

}

public class Row implements Serializable {
    @EmbeddedId
    @AttributeOverrides({
        @AttributeOverride(
            name = "masterId", 
            column = @Column(name = "masterId", nullable = false)),

        // Index is calculated 
        @AttributeOverride(
            name = "index", 
            column = @Column(name = "index", nullable = false, length = 18))
    })
    @NotNull
    private RowId id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "masterId", nullable = false, insertable = false, updatable = false)
    @XmlTransient
    private Master master;

    // Some other properties, getters and setters
}

我正在實現saveAll REST方法,從請求json序列化的對象是@OneToMany關系的完整表示。

我無法使用休眠自動行為,因為Row.RowId.index是使用舊式算法計算的。

因此,為此,我在create上執行以下操作:

@Transactional
public void createAll(Master master) throws Exception {

    // Save in a variable the row list
    List<Row> rows = master.getRows();

    // Nullify the rows
    master.setRows(null);

    // Persists the Master using an helper
    masterService.persist(master);

    for (Row row : rows) {

        // the row helper method has the legacy index algorithm
        rowService.persist(row);

    }
}

而且效果很好,插入操作沒有問題。

當我需要在插入之前刪除每一行時,問題就出現在更新上。 該代碼與insert完全相同,但是調用了deleteAll來執行HQL更新查詢。

@Transactional
public void updateAll(Master master) throws Exception {

    // Save in a variable the row list
    List<Row> rows = master.getRows();

    // Nullify the rows
    master.setRows(null);

    // Persists the Master using an helper
    masterService.merge(master);

    // Delete Everything before to save
    rowService.deleteAll(master);

    for (Row row : rows) {
        rowService.persist(row);
    }
}

這僅在此更新之前沒有行的情況下有效。 當有行時,hibernate刪除所有內容,插入沒有錯誤的新行,但不會將其持久化到數據庫中。

結果是清除所有當前的主行。

有沒有一種方法可以清楚地避免此問題? 我不想使用SQL來做這些,我不想將它們混合在一起...

非常感謝Davide。

@OneToMany關系的層疊類型設置為any。 這告訴Hibernate將更改同步到子級。

刪除cascadeType,一切正常。

public class Master implements Serializable {

    @Id
    @GeneratedValue(strategy = IDENTITY) 
    Long masterId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "master")
    private List<Row> rows = new ArrayList<Attribute>(0);

    // Getter and setters and other properties

}

非常感謝Davide。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM