Quentinb
Quentinb

Reputation: 510

What is the correct way to save Hibernate JPA child entity

I can for the life of me just not get my head around this.

We generated standard Entity objects using Intellij. I am now trying to save a parent child relationship.

I have 2 tables, event_person_register and event_user_role. This is what I have tried.

eventPersonRegister.setEventUserRolesByPersonRegisterId(new ArrayList<>());

EventUserRole eventUserRole = new EventUserRole();
eventUserRole.setEventPersonRegisterByUserRoleLinkPersonId(eventPersonRegister);
eventUserRole.setUserRole("ROLE_USER");
eventPersonRegister.getEventUserRolesByPersonRegisterId().add(eventUserRole);

eventPersonRegisterRepository.save(eventPersonRegister);

Only the parent is saved to the DB and not the child record. I have not placed any Cascade or fetch types on the OneToMany annotation. One registered person can have multiple roles.

Update 1:

I have tried the following from the eventPersonRegister entity:

@OneToMany(fetch=FetchType.LAZY, mappedBy = "eventPersonRegisterByUserRoleLinkPersonId", cascade=CascadeType.ALL)

But get error:

MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails

If I try from the user_role side, then I don't get any errors, but only the parent is saved and not the child.

Upvotes: 1

Views: 768

Answers (1)

hashiCode
hashiCode

Reputation: 509

As you said, you can use cascade on the OneToMany side.

If you don't want to use cascade, the other option is to:

//persist eventPersonRegister
eventPersonRegister.setEventUserRolesByPersonRegisterId(new ArrayList<>());
entityManager.persist(eventPersonRegister); 

//persist eventUserRole
EventUserRole eventUserRole = new EventUserRole();
eventUserRole.setUserRole("ROLE_USER");
entityManager.persist(eventUserRole);

//set the relation between eventUserRole and eventPersonRegister
eventUserRole.setEventPersonRegisterByUserRoleLinkPersonId(eventPersonRegister);  
eventPersonRegister.getEventUserRolesByPersonRegisterId().add(eventUserRole);

Upvotes: 1

Related Questions