1

JPA 控制器类方法 edit() 不检查实体是否已存在,而是添加新实体。我认为它应该抛出异常,因为我们想要编辑现有实体而不是添加新实体。谢谢。例如:

import controller.exceptions.NonexistentEntityException;
import controller.exceptions.PreexistingEntityException;
import entity.PersonNew;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

public class PersonNewJpaController implements Serializable {

    public PersonNewJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(PersonNew personNew) throws PreexistingEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(personNew);
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPersonNew(personNew.getId()) != null) {
                throw new PreexistingEntityException("PersonNew " + personNew + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(PersonNew personNew) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            personNew = em.merge(personNew);
            em.getTransaction().commit();
        } 
        catch (Exception ex) 
        {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) 
            {
                Long id = personNew.getId();
                if (findPersonNew(id) == null) {
                    throw new NonexistentEntityException("The personNew with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } 
        finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            PersonNew personNew;
            try {
                personNew = em.getReference(PersonNew.class, id);
                personNew.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The personNew with id " + id + " no longer exists.", enfe);
            }
            em.remove(personNew);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<PersonNew> findPersonNewEntities() {
        return findPersonNewEntities(true, -1, -1);
    }

    public List<PersonNew> findPersonNewEntities(int maxResults, int firstResult) {
        return findPersonNewEntities(false, maxResults, firstResult);
    }

    private List<PersonNew> findPersonNewEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(PersonNew.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public PersonNew findPersonNew(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(PersonNew.class, id);
        } finally {
            em.close();
        }
    }

    public int getPersonNewCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<PersonNew> rt = cq.from(PersonNew.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}

主班

PersonNew p = new PersonNew();
p.setId(new Long(22));
p.setName("Ahh adas");
p.setAddress("Salatiga, Indonesia");
p.setPhonenumber("+6281390989669");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("simple-jpaPU");
PersonNewJpaController con=new PersonNewJpaController(emf);

try 
{
 con.edit(p);
} 

catch (NonexistentEntityException ex) 
{
  Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
} 
catch (Exception ex) 
{
  Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
}

现在,如果 ID 为 22 的 Person 不存在,它会创建一个新的,而是应该更新实体,如果 ID 为 22 的实体不存在,它应该抛出异常。

4

1 回答 1

1

在您的 edit(PersonNew) 方法中,您有以下代码:

em.getTransaction().begin();
personNew = em.merge(personNew);
em.getTransaction().commit();

但是,合并的行为更像是创建或更新,而不是您想要的纯更新。如果您添加一点手动检查,您可以自己处理逻辑。就像是:

em.getTransaction().begin();
Long newId = personNew.getId();
PersonNew personOld = em.find(PersonNew.class, newId);
if (personOld == null)
    throw new NonexistentEntityException("The personNew with id "
        + newId + " no longer exists.");
personNew = em.merge(personNew);
em.getTransaction().commit();

这样,如果新 ID 不存在,您将抛出您想要的异常。

您还必须在此之后立即摆脱您的catch (Exception ex)位,否则它会干扰。但这没关系,因为这应该完成你在那里尝试做的事情,以及throws Exception从方法签名中删除可怕的部分。

于 2012-04-27T18:47:44.810 回答