JPA detached entity as part of a managed entity during merge

I have an in-application cache of some plain simple Entity beans (EJB 3.1, Glassfish, EclipseLink), so that I don't have to look them up in database with findById each time since application needs to be fast. These entity beans are read-only.

So for example entity bean Country or Currency is in the local cache.

Some process in the Java EE application occurs that wishes to update a complex entity bean (ie Customer), which uses the simple beans above (Country, Currency...).

What happens then is that, because the connection of simple entity beans to the JPA context is lost, when .merge() is attempted on the Customer bean, JPA wishes to save the simple entity beans as new records in the database, although these exist 100% in the database already, so I guess this is a "detached entity" problem.

Example.

Country country = getFromCacheByName("GB"); // detached entity, but exists in database
Customer customer = getCustomerFromJPA(); // existing JPA attached entity
customer.setCountry(country);
EntityManager.merge(customer); // pseudo code

How to fix the last line, or the bean (Customer) itself, so that it does not try to save the dependant object (Country) on .merge() ?

Thank you.


You should do a find() or merge() on the country before setting it in the Customer. Also, ensure it has the correct Id.

Merge on Customer should also work though, it is odd that it would attempt to insert the country if its Id was existing, but this could depend on how you have configured things. Are you cascading the merge on the country relationship?

Note that EclipseLink has its own cache. So your application cache is probably not needed.

链接地址: http://www.djcxy.com/p/61416.html

上一篇: Tomcat 7的EJB3.1和JSF问题

下一篇: JPA在合并期间作为管理实体的一部分分离实体