简体   繁体   中英

JPA Entity is not updated

I am using Servlet->EJB->JPA on Glassfish 4. Application deploys successfully.

When I run the servlet, it updates the entity with id=1 in db, but doesn't do anything for the one with id=2. No exception is thrown.

@WebServlet("/AnimalServlet")
public class AnimalServlet extends HttpServlet {

@EJB AnimalDAOLocal lOBAnimalDAO;

protected void doGet(....) {
    Animal lOBAnimal = lOBAnimalDAO.getAnimal(1); // gets OK
    lOBAnimal.setName("Animal1");  // sets OK
    lOBAnimalDAO.mergeAnimal(lOBAnimal); // updates in DB OK
    lOBAnimal = lOBAnimalDAO.getAnimal(2); // gets OK
    lOBAnimal.setName("Animal2"); // sets OK
    lOBAnimalDAO.mergeAnimal(lOBAnimal); // doesn't update in DB.
}

And Session Bean Methods are :

@Stateless(mappedName = "AnimalDAOMapped")
public class AnimalDAO implements AnimalDAOLocal {
    @PersistenceContext EntityManager em;

    public Animal getAnimal(int id) {
          return em.find(Animal.class, id);
    }

    public void mergeAnimal(Animal pOBAnimal) {
          em.merge(pOBAnimal);
    }
}

Persistence Unit Settings :

<persistence-unit name="JPATest" transaction-type="JTA">
    <jta-data-source>jdbc/animaltest</jta-data-source>
    <class>net.test.model.Animal</class>
</persistence-unit>

Use flush(); method, throw PersistenceException . Servlet catch that exception.

public void mergeAnimal(Animal pOBAnimal) throws PersistenceException {
    try {
        em.merge(pOBAnimal);
        em.flush();
    } catch (PersistenceException pe) {
        throw e;
    }
}

I solved the problem with the help of Chris' suggestion to turn on EclipseLink Logging ( Which I didn't know before ) .

The problem happened because of wrong @JoinColumn definition in the entity. And the first entity ( db=1 ) was committing by chance because of the existance of dummy data for this id which doesn't exist for other ids.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM