samedi 4 août 2018

I found common practice in Hibernates repository methods of checking if session is open before closing it. Isn't that redundand?

I have found that people very often create repositories methods like that:

public static Optional<Product> findOneById(Long id){
        Session session = null;
        try {
            session = HibernateUtil.openSession();
            Product product = session.find(Product.class, id);
            return Optional.ofNullable(product);
        }catch (Exception ex){
            ex.printStackTrace();
            return Optional.empty();
        }finally {
            if(session != null && session.isOpen()){
                session.close();
            }
        }
    }

I don't understand, what's the purpose of declaring session variable and assigning it to null, and at the end of double checking if it is not null and if the session is open? We are opening session on purpose in line number 4 so we already know, that session in open and it has to be in order to perform all of the other actions. I don't see any point in checking if session is open before closing it, but probably there is some point in doing it, because lots of examples show this construction. Could you please help me understand it?

Aucun commentaire:

Enregistrer un commentaire