Connor Butch
Connor Butch

Reputation: 688

JPA remove detached entity

I've just begun working with JPA and hibernate, and I have been able to insert query and update on one table, but I cannot seem to delete an entity. Even after I attach the entity with the merge function, the program insists it is detached. Here is the relevant code:

public User getUserByEmail(String email) throws DAOException{
    User user = null; 
    EntityManager em = null; //declare here for use in finally block
    try{                        
        //get em for use
        EntityManagerFactory factory = JPAUtil.getEntityManagerFactory();
        em = factory.createEntityManager();
        //setup return type as user
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<User> criteriaQuery = cb.createQuery(User.class);
        Root<User> userRoot = criteriaQuery.from(User.class);
        //populate the where clause
        criteriaQuery.where(cb.equal(userRoot.get("email"), cb.parameter(String.class, "email")));          
        Query query = em.createQuery(criteriaQuery);
        query.setParameter("email", email);
        //actually run the query on db
        user = (User) query.getSingleResult();
    }catch(Exception ex){
        DAOException dE = new DAOException(2, "getUserByEmail failed", ex);
        //TODO log
        throw dE;
    }       
    //cleanup
    finally{
        if(em != null && em.isOpen()){
            em.close();
        }
    }
    return user; //if not found, will still be null
}



@Override
/*
 * (non-Javadoc)
 * @see dao.IUserDAO#deleteUser(java.lang.String)
 */
public void deleteUser(String email) throws DAOException {
    EntityManagerFactory entityManagerFactory;
    EntityManager em = null;
    EntityTransaction trans = null;
    try{            
        //search user on email
        User user = getUserByEmail(email);          
        //check we found user with specified email
        if(user != null){
            //setup for interaction with database
            entityManagerFactory = JPAUtil.getEntityManagerFactory();
            em = entityManagerFactory.createEntityManager();
            //alterations of db must occur in scope of transaction
            trans = em.getTransaction();
            trans.begin();
            em.merge(user); //TODO update find to take transaction as parameter
            em.remove(user);
            trans.commit();
            //explicitly flush here
            em.flush();             
        }else{
            //TODO we didn't find the user
        }

    }catch(Exception ex){
        DAOException dE = new DAOException(6, "delete failed", ex);
        //TODO log
        trans.rollback();
        throw dE;
    }finally{
        if(em != null && em.isOpen()){
            em.close();
        }
    }       
}

And here is the output from the eclipse console: "Removing a deattached instance of User#1".

Could someone explain why this bean is still deattached after I explicitly called merge? Also, how would I fix this problem? Thanks.

Upvotes: 1

Views: 1275

Answers (1)

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

The content of the specified detached entity object is copied into an existing managed entity object with the same identity (i.e. same type and primary key). If the EntityManager does not manage such an entity object yet a new managed entity object is constructed. The detached object itself, however, remains unchanged and detached.

Even after merge the detached object itself remains detached, merge will return the new created merged entity

user = em.merge(user); //TODO update find to take transaction as parameter
em.remove(user);

Upvotes: 1

Related Questions