Reputation: 6532
for simplicity, here is my simplified model:
I got 2 entities:
@entity
public class Student {
int id;
School school
...
}
and the school is an entity as well
@entity
public class School {
int id;
...
}
im trying to pull a lot of data from a text file. some students have the same school instance, i wouldn't like multiple schools in my database with the same name, so my goal is to save each student in the student db , while making sure that 2 different students with the same school , wont create 2 entries in my school db.
problem is when i try to persist the students, it gives me an error: "detached entity passed to persist" , how do i tell hibernate, that the school in the student class is already exists in the database , and that it should use it instead?
thanks
Upvotes: 1
Views: 1927
Reputation: 1140
Assuming associations are already set:
Make sure you are working with the persisted Student entity. Do a search for the student entity, and set the school -> student to the student entity returned from the search.
entity.find ( Student.class, student_id)
Otherwise, make sure the associations are annotated before doing the above.
Upvotes: 0
Reputation: 597036
Map it with @ManyToOne(cascade=ALL)
.
"the same name" would not suffice though, you should have the same ID. For that to work, you'd need to make sure your School
object is taken from the DB before setting it to the Student
Upvotes: 3
Reputation: 1018
There is a method on the session called merge(). Use that instead of saveOrUpdate();
Upvotes: 0