B. Kemmer B. Kemmer - 26 days ago 19
Java Question

Hibernate Add Model with OneToMany

I have got an PersonModel which has an address.

Looks like that:

public class PersonModel {
@ManyToOne(fetch = FetchType.LAZY)
private AddressModel address;
}

public class AddressModel {
private String street;
private String city;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "address", cascade = CascadeType.ALL)
private Set<PersonModel> persons;
}


Now, when I get this JSON from my Client:

{
"person": {
"address": {
"street": "Examplestreet",
"city": "Examplevillage"
}
}
}


And try to save it like that:

personModelRepository.save(myJSON.person);


Hibernate will always throw a TransientPropertyValueException.


object references an unsaved transient instance - save the transient instance before flushing


Do I really have to save every single DB-Entry related to person first or is there another way?

Answer

Try adding CascadeType.ALL at the @ManyToOne annotation.

This achieves that your Person gets saved automatically if you save your Address

Comments