1

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

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.