2009-04-30 115 views
1

我有2個EJB 3實體Bean刪除:JPA 2聯鎖實體類

@Entity 
public class Organisation 
{ 
    @Id 
    @Column(length = 64) 
    private String guid; 

    private String name; 

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) 
    @JoinColumn(name = "home_unit_fk", nullable = true) 
    private Unit homeUnit;   
} 

@Entity 
public class Unit 
{ 
    @Id 
    @Column(length = 64) 
    private String guid; 

    private String name; 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "organisation_fk", nullable = false) 
    private Organisation organisation; 

    @ManyToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "parent_unit_fk", nullable = true) 
    private Unit parentUnit; 

    @OneToMany(mappedBy = "parentUnit", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE) 
    @OrderBy("shortName") 
    @OptimisticLock(excluded = true) 
    private Set<Unit> childUnits; 
} 

如果我使用標準道街組織的一項刪除:

public int deleteByGuid(final String guid) 
{ 
    final Query query = entityManager.createQuery("delete from " + getPersistentClass().getName() + " where guid = :guid"); 
    query.setParameter("guid", guid); 
    return query.executeUpdate(); 
} 

,但我得到了以下異常:

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:無法刪除或更新父行:外鍵約束失敗(configunit, CONSTRAINT FK27D184F5D4393D FOREIGN KEY(organisation_fk)參考文獻organisation(​​))

我不明白。我究竟做錯了什麼? JPA/Hibernate不應該在單元和組織內的同一事務中執行刪除操作嗎?

回答

2

批量刪除查詢不會將對象加載到內存中,並且會繞過關聯中指定的任何級聯。

public int deleteByGuid(final String guid){ 
    Organization org = entityManager.find(Organization.class, guid); 
    entityManager.remove(org); 
} 

如果使用查詢做批量更新,操作是直接委託給數據庫:

,我會編寫你的刪除方法。如果您希望刪除子對象,則必須在「數據庫」級別設置DELETE CASCADE觸發器。

通過加載對象並將其刪除,Hibernate將在「對象」級別觸發級聯。

更多信息,請訪問:http://twasink.net/blog/2005/04/differences-in-behaviour-between-hibernate-delete-queries-and-the-old-way/

+0

確定這是非常合情合理的......不過......我已經嘗試過了,我得到以下異常: 引起:javax.persistence.PersistenceException:org.hibernate作爲.PropertyValueException:在org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:614) \t在org.hibernate.ejb.AbstractEntityManagerImpl.remove(AbstractEntityManagerImpl Unit.organisation \t:非空屬性引用null或瞬態值.java:259) 任何想法?乾杯。 – TiGz 2009-05-05 16:21:08