How to remove Entity Bean in CMP stateless session bean in EJB 3.0
Posted on 2009-05-04
EJB 3.0 is new to us. We just started to migrate our EJB2.1 to EJB3.0. We are having issues. Can anyone help?
The table has a unique index#2 besides the primary key.
The following transaction (in a single themod) works great in container managed session bean in EJB 2.1:
1. find theEntity using theValue of theColumn for index#2;
2. if( theEntity exists ) then delete theEntity;
3. insert newEntity with new primary key but the same theValue of theColumn for index#2.
The method is translated in an EJB 3.0 like below:
private EntityManager em is global in the session bean and is injected in PersistenceContext;
annotation TransactionAttribute(REQUIRED) for the method;
namedQuery.getResultList() in 1. (Couldn't use getSingleResult since sometimes it returns none);
em.remove( theEntity ) in 2.;
em.persist( newEntity ) in 3..
The first time calling this method, no problem. The newEntity gets inserted. The second time, we get DuplicateKeyException; If we add em.flush() in step 2 after the em.remove( theEntity ), we get OptimisticLockException.
What's wrong with this translation? Or what else I have to do in order for this translation to work? Thanks!!!