org.hibernate.TransientObjectException使用CascadeType.ALL持久保留嵌套子级 [英] org.hibernate.TransientObjectException persisting nested children with CascadeType.ALL
问题描述
我有一个名为 Human
的类,其中包含狗的列表:
I have a class called Human
which has a list of dogs :
@Entity
public class Human {
@Id
@GeneratedValue
private Long id;
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL}, orphanRemoval = true)
private Set<Dog> dogs = new HashSet<>(List.of(new Dog()));
...
}
狗类 Dog
有一个小狗列表:
@Entity
public class Dog {
@Id
@GeneratedValue
private Long id;
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, orphanRemoval = true)
private Set<Puppy> puppies = new HashSet<>(List.of(new Puppy()));
}
@Entity
public class Puppy {
@Id
@GeneratedValue
private Long id;
}
当我尝试创建一个有狗的新人类并且该狗有一只小狗时,我使用带有Spring的Hibernate JPA存储库来保存该人类:
When I try to create a new human that has a dog and the dog has a puppy and I save the human using an Hibernate JPA repository with Spring :
Human human = new Human();
Set<Dog> dogs = new HashSet<>();
Dog dog = new Dog();
dog.setPuppies(new HashSet<>(List.of(new Puppy())));
dogs.add(dog);
human.setDogs(dogs);
humanRepository.save(human);
我收到以下错误:
org.hibernate.TransientObjectException:对象引用了一个未保存的瞬态实例-在刷新之前保存该瞬态实例:com.test.Puppy
但是,如果我创建具有默认值的人类并将其保存在人类资源库中,它将起作用并保存小狗.
But if I create the human, with the default values and save him with the human repository, it works and it saves the puppy.
Human human = new Human();
humanRepository.save(human);
我不明白为什么不自动保存小狗,并且我不想使用单独的存储库来保存小狗.当狗定义 CascadeType.ALL
时,Hibernate是否应该自动保存我的小狗?就像他们在此stackoverflow上说的那样:针对孩子的孩子的JPA Hibernate级联类型
I don't understand why the puppy is not automatically saved and I don't want to use a separate repository to save the puppy. Shouldn't Hibernate automatically save my puppy as the Dog defines CascadeType.ALL
? Just like they say on this stackoverflow : JPA Hibernate cascade type for child of child
推荐答案
尝试更改级联类型以保留在关联注释中
try to change cascade type to persist in your association annotation
@OneToMany(获取= FetchType.EAGER,级联= {CascadeType.PERSIST},orphanRemoval = true)
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST}, orphanRemoval = true)
这篇关于org.hibernate.TransientObjectException使用CascadeType.ALL持久保留嵌套子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!