0

I have a method in Controller:

 @RequestMapping(value = "/children", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void createChild(@RequestBody CreateChildRequestDTO childDTO) { Long guardianId = Long.parseLong(childDTO.getGuardianId()); Child child = childDTO.getChild(); Guardian guardian = guardianService.findById(guardianId).get(); boolean isExist = childService.isExist(child.getChildFullName(), child.getPassword(), child.getPhoneNumber()); if (isExist) { child = childService.findChildByNameAndPass(child.getChildFullName(), child.getPassword()); guardian.addChild(child); } else { guardian.addChild(child); childService.createChild(child); } } 

And also I have created a many-to-many relationship in Guradian class:

@ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "guardian_child", schema = "cheer", joinColumns = @JoinColumn(name = "guardianid"), inverseJoinColumns = @JoinColumn(name = "childid")) private List<Child> children = new ArrayList<>(); 

When I run the code and execute line guardian.addChild(child) child is added to guardian's list, but not created a new record in table. How to fix it? Commit change in objects relation?

4
  • 1
    You never save the changes Commented Feb 7, 2020 at 10:47
  • block else is working. And new record adds to guardian_child table Commented Feb 7, 2020 at 10:49
  • and i don't understand how is it possible? Commented Feb 7, 2020 at 10:50
  • Well without the code for childService.createChild(child); I am not sure how you expect that to be answered. I would guess because childService saves the child?? Commented Feb 7, 2020 at 10:54

1 Answer 1

2

As @Jens suggested in the comment, you're never saving changes to the database.

There are two ways you can resolve this issue:

  1. You can run the code within a transaction, then hibernate will take care of dirty-checking and commit all the changes to the parent to the database.
  2. You can save guardian by calling something like that at the end of the method:

    guardianService.save(guardian); 
Sign up to request clarification or add additional context in comments.

5 Comments

@Krazim00da the fact that the code is working and entities have relationships, doesn't mean they are saved to the database
i checked the records in db...and after else there is new record.
@Krazim00da then what is your problem?
identical code in if(true) isn't working. and new record is not added
how do i must realise save method?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.