2014-11-23 49 views
1

請參閱方法testCollections()。兩個對象被創建並被插入到集合中。然後其中一個從收藏中刪除。一切正常,單行添加在數據庫中。 但是,如果我們在從集合中刪除對象之前執行任何sql查詢,hibernated會爲新對象分配PK,並且它們都存儲在數據庫中,無論集合中是單個對象... 任何想法如何將它解釋爲休眠?Hibernate不會在特定情況下從子集中刪除對象

@Entity 
    @Table(name = "animalowner") 
    public class Owner { 
     @Id 
     @Column 
     private Long id; 
     @Column(name = "owner_name") 
     private String name; 
     @OneToMany(fetch = FetchType.EAGER, targetEntity = Animal.class, cascade = { CascadeType.ALL }, orphanRemoval = true) 
     @JoinColumn(name = "owner_fk") 
     private Set<Animal> animals; 
     ...... 


@Entity 
@Table(name = "animals") 
public class Animal { 
    public Animal(String name, Owner owner) { 
     this.name = name; 
     this.owner = owner; 
    } 
    public Animal() { 
    } 
    @Id 
    @GeneratedValue(generator = "animal_generator") 
    @SequenceGenerator(name = "animal_generator", sequenceName = "animal_sequence") 
    private Long id; 
    @Column(name = "cat_name") 
    private String name; 
    @ManyToOne(targetEntity = Owner.class, fetch = FetchType.EAGER) 
    @JoinColumn(name = "owner_fk") 
    private Owner owner; 
    ......... 



@Component 
public class SomeService { 
..... 
@Override 
    @Transactional 
    public void testCollections(){ 
     Owner owner = repository.loadOwnerById(1L); 
     Set<Animal> animals = owner.getAnimals(); 
     Animal animal1 = new Animal("animal1", owner); 
     Animal animal2 = new Animal("animal2", owner); 
     animals.add(animal1); 
     animals.add(animal2); 

     //IF any SQL called here, hibernate assigns primary keys for animal1 and animal2, 
     //and 2 objects are saved to database. 

     animals.remove(animal1); 
    } 
..... 

回答

1

這是因爲用戶連接到當前運行PersistenceContext:

Owner owner = repository.loadOwnerById(1L); 

,並添加任何動物的動物收集的時刻:

@OneToMany(fetch = FetchType.EAGER, targetEntity = Animal.class, cascade = { CascadeType.ALL }, orphanRemoval = true) 
@JoinColumn(name = "owner_fk") 
private Set<Animal> animals; 

Upon executing a query the flush mechanism kicks iñ。 Hibernate dirty checking mechanism檢測到所有者發生了更改,並且它與數據庫同步任何更改。

transitive persistence mechanism是要保存所有新的兒童實體:

如果一個瞬時的或脫的孩子被一個持久 的父對象引用,它被傳遞到saveOrUpdate()方法

這就是爲什麼動物得到保存沒有任何明確的沖洗。

+0

嗨,弗拉德。感謝您詳細解釋。 無論如何,它不是休眠期望的行爲。 這裏的解決方法可能如下。從集合中移除後,告訴hibernate刪除分配了PK的對象。像HibernateTemplate.delete(對象實體)。 這對我有用。 – whatswrong 2014-11-24 09:13:47

相關問題