Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity must be managed to call remove

What's going on here?

@Stateless
@LocalBean
public class AppointmentCommentDao {
    public void delete(long appointmentCommentId) {
        AppointmentComment ac = em.find(AppointmentComment.class, appointmentCommentId);
        if (ac != null)
        {
            em.merge(ac);
            em.remove(ac);
        }
    }
    @PersistenceContext
    private EntityManager em;
}

On the call to remove I get an IllegalArgumentException with the message being Entity must be managed to call remove: ...., try merging the detached and try the remove again.

like image 837
Steve Avatar asked Feb 18 '12 05:02

Steve


2 Answers

In your case merge is not needed, because ac is not deattached in any point between em.find and em.remove.

In general when entity is deattached, EntityManager's method merge takes entity as argument and returns managed instance. Entity given as argument does not transform to be attached. This is explained for example here: EntityManager.merge. You have to go for:

    AppointmentComment toBeRemoved = em.merge(ac);
    em.remove(toBeRemoved);
like image 119
Mikko Maunu Avatar answered Nov 12 '22 17:11

Mikko Maunu


Try this:

entity = getEntityManager().getReference(AppointmentComment.class, entity.getId());
getEntityManager().remove(entity);
like image 45
Ismac Avatar answered Nov 12 '22 17:11

Ismac