简体   繁体   中英

hibernate - saving entity with an entity in it (that already exists in the db)

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

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

There is a method on the session called merge(). Use that instead of saveOrUpdate();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM