简体   繁体   中英

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?

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); Person p=new person(); p.setCity(city);

3- save the Person object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM