Pregunta

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>
¿Fue útil?

Solución 2

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.

Otros consejos

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;
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top