简体   繁体   中英

session.flush() caused Null Pointer Exception in Hibernate

I am trying to save objects in a loop, and I don't want to stop my work when it come across errors, so my code looks like follows:

for(Model model:list){
 try {

                if (model != null) {
                    getHibernateTemplate().saveOrUpdate(model);
                    getHibernateTemplate().flush();
                } 
            } catch (Exception e) {
               log.error(e);
                if (model!= null) {
                    getHibernateTemplate().getSessionFactory().evict(Model.class, model.getId());
                }
                getHibernateTemplate().evict(model);
            }
}

It works fine except when one object saving failed, all the rest object failed with java.lang.NullPointerException. Absolutely the Hibernate session is not null according to my debug tracing. Is there anything wrong with my code? Any comments would be great appreciated!

When the session throws an exception, you should not continue with it because it is in an inconsistent state. You should do the saves inside a transaction on rollback everything if an exception is thrown.

Search for "don't flush the Session after an exception occurs" for more info

Also, this part of your code looks weird:

if (model!= null) {
   getHibernateTemplate().getSessionFactory().evict(Model.class, model.getId());
}
getHibernateTemplate().evict(model);

What it is supposed to do when model is null? Shouldn't you put the last line inside the if statement?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM