Link to home
Start Free TrialLog in
Avatar of kmapper
kmapper

asked on

How to persist an unmanaged property object

Hi,
I'm using an EJB 3.0 entity bean.

I want to save a new Employee entity bean and associate it to the department id = 44;

The way it works, I need to
1-fetch the department entity bean
2-Set the department into the employee
3-Save the employee.

If you notice, the first step is useless since I already know the Id of the department. Why should I fetch it and get a managed entity bean?

I would expect to be able to do that kind of save:

Department dep = new Department();
dep.setId(44);

Employee emp = new Employee();
emp.setDepartement(dep);

entityManager.persist(emp);

But that doesn't work because the framework forces to have a managed object as the department. I would have thought that when I set CascadeType to nothing it would do the trick but it doesnt.

Is there any workaround for this ?

Thanks!



ASKER CERTIFIED SOLUTION
Avatar of Mr_It
Mr_It

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mr_It
Mr_It

Thanks :-) I know it's still an INSERT and UPDATE statement, while it could be done in 1 INSERT statement if you use native SQL... This is just one disadvantage of using an ORM like JPA. It does not always do the most performant things.

Keep in mind that your managed Employee entity is not in sync anymore after such and UPDATE (or DELETE) statement. Maybe I should have put an em.clear() call as well after the flush.
 
Avatar of kmapper

ASKER