Retrieving list of outdated objects with Hibernate

2

When I manually enter an object in MySQL via terminal, Hibernate does not retrieve the list with the updated object, it is always the same as the last query, as if it were taken from a cache.

I tried to do this but it did not work.

  public ArrayList<Praga> listarTodasPragas() {     
        ArrayList<Praga> listaPragas = new ArrayList<>(session.createCriteria(Praga.class).list());
        for(Praga p : listaPragas){
            session.refresh(p);
        }
        return listaPragas;
   }

Note: The session.close () I close soon after calling another method.

    
asked by anonymous 21.11.2014 / 14:00

2 answers

2
public Lits<Praga> listarTodasPragas = new ArrayList<>();

public List<Praga> getListarTodasPragas(){

    if(listarTodasPragas == null){
        return   listarTodasPragas = session.createCriteria(Praga.class).list());
    }
    return  listarTodasPragas;
}
    
21.11.2014 / 17:23
0

You are refreshing every Praga object, this causes a given object to be updated with the state of its attributes in the database, but does not make all objects of that type updated, nor does it with which a new entity inserted by another process is rescued from the base.

One option is to invoke the clear() method of the session, thus causing all entities to be detached, so that when requesting entities again, the session will fetch them from the database, not from the cache.

Example:

  public ArrayList<Praga> listarTodasPragas() {     

        session.clear(); // desatacha todas as entidades da sessão

        ArrayList<Praga> listaPragas = new ArrayList<>(session.createCriteria(Praga.class).list());
        return listaPragas;
   }

Consider the implications of this on your system: All entities will be unpinned. If there are pending changes in context, these changes will not be persisted in the database. So that's probably not the best way to do it. Perhaps the invoking process for listarTodasPragas , the one who created the session, is the one who should clean it.

    
21.11.2014 / 15:50