简体   繁体   中英

References to one to many relationship objects doesn't update

class Person
{
    List<Skill> skills;
    //... other stuff
}
class Skill{
    //stuff
}

mySkillList.add(skill);
person.add(skill);

person.getSkills();      //all skills have ID attribute null

repository.save(person);

person.getSkills();    //all skills now have ID not null, after saving

But when I iterate over mySkillList , none of the skills have IDs (an attribute named id is still null).

I'm trying to understand what is going wrong, why is my list of objects not getting updated after saving, when the original person objects' list of skills gets updated.

I'm using Spring-Data, if that makes any difference.

Update

So seems like the behavior I get, is expected according to the docs. But my requirement is to get the IDs of some skills that are stored in mySkillList , not all those are present in the Person object.

I can of course, get all the skills from Person object before and after saving, to figure all the skills that are new, but then the newly created skills loose the order in which they were saved in mySkillList which is what I want. In other simple words, I need all the skills that are new in the same order as I've inserted them in the Person's object. Any help is greatly appreciated.

Thanks

From the Javadoc for SDC save :

Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.

Spring Data works on ordinary POJOs, and its contracts specifically say that you might not even get the same instance back, depending on the persistence setup. You'll need to reload the skill objects from their repository after saving.

If you want the skill objects to be shared between the various in-memory data structures, you need to save each skill as you construct it before you add it to the list and/or Person .

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