[英]org.hibernate.TransientObjectException persisting nested children with CascadeType.ALL
I have a class called Human
which has a list of dogs:我有一个名为
Human
的 class 有一个狗列表:
@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()));
...
}
The dog class Dog
has a list of puppies:狗 class
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;
}
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:当我尝试创建一个有狗的新人类并且狗有一只小狗并且我使用 Hibernate JPA 存储库和 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);
I get the following error:我收到以下错误:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: 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);
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
? Hibernate 不应该在 Dog 定义
CascadeType.ALL
时自动保存我的小狗吗? Just like they say on this stackoverflow: JPA Hibernate cascade type for child of child就像他们在这个 stackoverflow 上说的那样: JPA Hibernate 级联类型用于子级
try to change cascade type to persist in your association annotation尝试更改级联类型以保留在您的关联注释中
@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST}, orphanRemoval = true) @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST}, orphanRemoval = true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.