Recovering List of Outdated Objects with Hibernate

Asked

Viewed 290 times

2

When I manually insert an object in Mysql via terminal, Hibernate does not recover the list with the updated object, it is always the same as the last query, as if it were taken from some cache.

I tried to do it but it didn’t 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: A Session.close() I close right after calling another method.

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;
}
  • 3

    welcome to Stackoverflow in English, it would be ideal for you to explain your solution and also format your code, to format the code just give 4 spaces { }.

  • 1

    That’s not quite my problem, and that condition will never be TRUE

  • when you load the page in question will be called getListarToday.

0

You are making the refresh of each object Praga, this causes a given object to be updated with the state of its attributes in the database, but does not cause all objects of that type to be updated, nor will it be rescued from the database a new entity inserted by another process.

One option is to invoke the method clear() of the session, thus causing all entities to be detached, so that when requesting entities again, the session will retrieve them from the database and 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 unchecked. If there are pending changes in the context, these changes will not be persisted in the database. So this is probably not the best way to do it. Perhaps the summoning process of listarTodasPragas, the one who created the session, is the one who should clean it.

  • OK Caffé I had used clear, but I used it after receiving the list as soon as I put the results. Thank you. I will test this solution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.