After an UPDATE, I execute a select but the data is not updated

3

I'm working JPA, I run the following update:

  public int EditarUsuario(UserSys us) {

    EntityManager em = getEntityManager();
    em.getTransaction().begin();
    try {
        Query q = em.createNativeQuery("UPDATE 'user_sys' "
                + "SET "
                + "'USER_NOM' = ?, "
                + "'USER_ESTADO' = ?, "
                + "'USER_ROL' = ? "
                + "WHERE 'USER_ID' = ?; ");
        q.setParameter(1, us.getUserNom());
        q.setParameter(2, us.getUserEstado());
        q.setParameter(3, us.getUserRol());
        q.setParameter(4, us.getUserId());
        int v = q.executeUpdate();
        em.getTransaction().commit();
        return v;
    } catch (javax.persistence.NoResultException ex) {
        return 0;
    } finally {
        em.close();
    }
}

It works perfectly, since when I run the query on mysql I see the update directly, however when I do the select * from of that table I do not see the changes in jpa:

 public List<UserSys> Buscartodos() {
   EntityManager em = getEntityManager();
   em.clear();

    try {
        Query q = em.createNativeQuery("SELECT * FROM user_sys ;", UserSys.class);
       List<UserSys> lista=q.getResultList();

        return lista;

    } catch (javax.persistence.NoResultException ex) {
        return null;
    } finally {
        em.close();
    }

}

I have done inserts and they work and update the data, in this case that may be happening?

    
asked by Daniel ORTIZ 25.04.2016 в 23:14
source

2 answers

6

After closing the transaction and closing the EntityManager , the transactions are correctly perpetuated in your database and future queries, because they are new transactions, will be able to read the changes made by previous transactions.

Yours is a very peculiar case, since you explain that in spite of closing the transaction and the EntityManager , it is as if the changes made in the database have not been reflected, assuming that these operations are executed by sequentially and that all sessions have been closed before executing your SELECT statement.

In any case, you can go to the methods EntityManager#flush and EntityManager#clear , in that order, so that all the operations are executed and you can see the reflected changes. The code of your query would be as follows:

public List<UserSys> Buscartodos() {
    EntityManager em = getEntityManager();
    em.flush();
    em.clear();
    try {
    /*
        resto de tu código
        incluye cerrar este bloque try y aplicar finally
        para cerrar los recursos
    */
}
    
answered by 25.04.2016 / 23:59
source
3

Fixed by adding

em.flush();
em.clear();'

Before running the select * from

    
answered by 25.04.2016 в 23:42