简体   繁体   English

session.flush()导致Hibernate中的Null Pointer异常

[英]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. 除了一个对象保存失败,其余所有对象都失败并出现java.lang.NullPointerException之外,它工作正常。 Absolutely the Hibernate session is not null according to my debug tracing. 根据我的调试跟踪,Hibernate会话绝对不为空。 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? 您不应该将最后一行放在if语句中吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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