Reputation: 3281
I have a problem with detached entity passed to persistence. I thought I knew what detached entity is, but apparently this is too much for me... So Anyway I am trying to create a Person object that has an Interviewer object that has an Office object and every time I try to persist Person I get the exception (Office is the detached entity in this case). Relevant code looks like this:
@Before
public void setup() {
Person person = PersontHelper.createPerson();
person.getInterviewer().setOffice(officeDao.find(1));
personDao.create(person);
interviewers = service.getAllInterviewers();
}
the createPerson()
is a static method of a helper class:
public static Person createPerson(){
Interviewer interviewer = Interviewer.createInterviewer();
Collection<Subject> skills = new HashSet<SubjectO>();
Person person = new Person();
person.setInterviewer(interviewer);
person.setSkills(skills);
return person;
}
and finally createInterviewer()
:
public static Interviewer createInterviewer(){
Office office = new Office(1, 1, "Bristol");
Interviewer interviewer = new Interviewer();
interviewer.setFirstname("John");
interviewer.setSurname("Bloggs");
interviewer.setEmail("john.example.com");
interviewer.setJobTitle(30);
interviewer.setOffice(office);
interviewer.setInterviews(new HashSet<Interview>());
return interviewer;
}
You might notice that helper method that creates Interviewer already sets its office, but this is used for other tests, and since the office with the same properties is stored in test database I use officeDao
to get it and set it as Interviewer's office. I tried multiple combinations of what I posted here but I get no positive results so far. I don't understand why it complains about Office being detached, because it did even when I wasn't getting it from db - in other words all three object were new and they were not associated with persistence context. I've read http://java.boot.by/scbcd5-guide/ch06.html but still cannot work it out. What am I doing wrong here?
Upvotes: 0
Views: 156
Reputation: 11926
The basic reason behind this exception is the entity which you want pass to persist is not associated with the EntityManager object. Anyways if you are using entityManager.persist(entity) then try to use entityManager.merge(entity).
One more thing is you should check your entity have updated or not for that you can use flush() method of EntityManager class.
Ex. entityManager.flush();
Upvotes: 2
Reputation: 1097
Where do you open the transaction ?
If your transaction management is at DAO level, this means your Office object has been loaded in a transaction opened by OfficeDao and is considered as detached in the next transaction opened by personDao.
Ideally, your transaction management should be handled by your helper method or a service layer.
Otherwise, to fix this you must either load your Office object or merge it inside your personDao.create() method.
Upvotes: 1