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!
HibernateTemplateis quite old. Its usage is highly discouraged for a long time. Hibernate 4.x doesn't support it anymore. Why do you still use it?