I tried to search for an answer to this problem to no avail, so I will post my problem.
Domain object:
Person, Education and School; each maps to a table in the DB. An education is defined as an object containing a school, a start date and an end date. A person can have multiple educations (i.e. have gone to the same school but at different times and receiving different degrees). I have an unique constraint on the school name as I don't want the same school appear multiple times in the database.
Problem:
During the import process, I would loop through the education for a person and create the school if it's not already existed in the DB. The problem arises when the person goes to the same school multiple times and the school was not previously existed in the DB.
Example:
Code:
Person A -> Education 1 -> School A
-> Start Date A
-> End Date B
-> Education 2 -> School A
-> Start Date C
-> End Date D
I am doing a big save at the end of each person. When I try to persist PersonA, I get the unique constraint violation on school name. I understand why it's doing it: when the code does a lookup in the DB to check to see if SchoolA exists in the DB, it's not at that point. That's why it created 2 instances of Java School object containing the same data. When Hibernate tries to persist SchoolA in Education2, SchoolA already exists in the database. What I don't get is how come hibernate doesn't detect SchoolA already exists when trying to save for the second time. Any help would be appreciated.