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