Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7859613
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T21:57:23+00:00 2026-06-02T21:57:23+00:00

JPA Controller class method edit() does not check if entity already exist instead adds

  • 0

JPA Controller class method edit() does not check if entity already exist instead adds new entity. Where I think it should throw an exception because we want to edit an existing entity not add a new one. Thanks.
For example:

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();
        }
    }

}

Main Class

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);
}

Now if Person with ID 22 does not exist it creates a new one instead it was supposed to update the entity and if entity with ID 22 does not exist it should throw an exception.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T21:57:27+00:00Added an answer on June 2, 2026 at 9:57 pm

    In your edit(PersonNew) method, you have the following code:

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

    However, merge acts more like Create or Update, not the purely-Update which you desire. If you add a little bit of manual checking, you can handle the logic yourself. Something like:

    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();
    

    That way if the new ID doesn’t exist, you throw the exception you were intending.

    You’ll also have to get rid of your catch (Exception ex) bit immediately following that, or it will interfere. But that’s okay, since this should accomplish what you were trying to do there, as well as removing the scary throws Exception bit from the method signature.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a JPA entity similar to; public class Inventory { private String productname;
With JPA I do not need to code the SQL for every new attribute
I have a domain object class User (it is a JPA entity): @Entity public
Simple JPA/JPQL question. I have an entity with a ManyToMany relationship: @Entity public class
We are using JPA entity beans as our model for Spring MVC controller on
I am using JPA, Hibernate and Spring MVC. In the controller class all the
My jpa looks like below public class TESTClass implements Serializable { ... private String
I have a JPA object which has a many-to-many relationship like this: @Entity public
A have a JPA entity that has timestamp field and is distinguished by a
I'm using JPA but I'm not sure how to use it for relation between

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.