Elbbard
Elbbard

Reputation: 2164

org.hibernate.TransientObjectException persisting nested children with CascadeType.ALL

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()));

    ...
}

The dog class Dog has a list of puppies :

@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 :

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? Just like they say on this stackoverflow : JPA Hibernate cascade type for child of child

Upvotes: 1

Views: 436

Answers (1)

taha
taha

Reputation: 44

try to change cascade type to persist in your association annotation

@OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST}, orphanRemoval = true)

Upvotes: 1

Related Questions