You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@openjpa.apache.org by Chadwick Baatz <cb...@us.ibm.com> on 2007/09/11 20:52:50 UTC
Detached Object?
I'm new to using JPA, so I might be misinterpreting how the detached object
concept should work. The problem I am having is integrating JPA into a
service based system. I have an entity A that I would like to share
between many different entities (B). There will be time when more than one
request arrives where different entity B's will redefine A. So the
instance of A are not "detached" but rather new duplicates of a unique
entity. I can catch duplicate entities by looking them up based on a
unique key, but when I try to merge that object the entity manager
attempts to insert the new value. This is true even though there is a
defined set of unique columns and I've set the identity value. Should I
get the persisted entity then manually update the fields? It seems to me
that the merge command should be able to handle this.
DAO Code:
public A saveEntity(A entity)
{
EntityTransaction transaction = this.manager.getTransaction();
transaction.begin();
// Determine if the injection is new or a duplicate
if(entity.getId() <= 0)
{
Query query = this.manager.createNamedQuery("findByUNK");
query.setParameter("field", entity.getField());
query.setParameter("className", entity.getClassName());
query.setParameter("url", entity.getUrl());
query.setParameter("injectionType", entity.getInjectionType());
List entities = query.getResultList();
A persistedEntity = (A)(entities != null && entities.size() > 0 ?
entities.get(0) : entity);
entity = persistedEntity ;
}
if(entity .getId() > 0 || this.manager.contains(entity ))
{
entity = this.manager.merge(entity );
}
else
{
this.manager.persist(entity );
}
transaction.commit();
return entity ;
}