First:
More over in my database schema I have foreign key contraint on person.conference_room_code that references conference_room.code column.
Your FK should reference the PK of the referenced entity. In the instant case, you should have person.conference_room_id
which references conferenceroom.id
. If you want your code
to be the identifying field for the ConferenceRoom
entity, then don't use a surrogate key. If the code
column isn't a PK candidate, then it is also not an FK candidate.
Second:
Copy the state of the given object onto the persistent object with the same identifier. If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge"
Make a transient instance persistent. This operation cascades to associated instances if the association is mapped with cascade="persist"
I think you have confused merge
with persist
. From what I can tell by the provided code, you are creating a new ConferenceRoom
and not modifying an existing one. Therefore, merge
is not going to do what you want it to do. Try changing your (provided) method to the following:
public ConferenceRoom getNewConferenceRoom(Person p) {
ConferenceRoom r = new ConferenceRoom();
r.setCode("MyUniqueGeneratedCode");
r.getPeople().add(p);
// sessionFactory is spring injected member
sessionFactory.getCurrentSession().persist(r);
}
These things should fix the issues you have raised.