user5488223 user5488223 - 3 months ago 28
JSON Question

Jackson save a nested object to database

I am using jackson for converting a json to java objects.

java object:

class Person{
Long id;
String name;
City city;
}

class City{
Long id;
String cityName;
}


jcson conversion:

List<Person> personList = objectMapper.readValue(json, new TypeReference<List<Person>>() { });


When saving the person, i get the following error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: model.City


Can you please advise?

Answer

You have to include cascade="all" (if using xml) or cascade=CascadeType.ALL (if using annotations) on City attribute in your Person entity.

this is due to the fact that you are trying to save an entity which is referenced to an unsaved one.

if you dont want to delete the City record when deleting a Person you have to pass by theses steps: 1- getting the city from database : City city=session.get(id,City.class);

2- setting person's city : Person p=new person(); p.setCity(city);

3- save the Person object.