我的线程执行时,有时会收到这个奇怪的错误。这可能与什么有关?
2011-Jun-25 09:05:22,339 ERROR AssertionFailure:45 - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session) org.hibernate.AssertionFailure: null id in com.inrev.bm.bean.IRKeyWordTweet entry (don't flush the Session after an exception occurs) at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:78) at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:187) at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:143) at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:219) at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:49) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137) at com.inrev.bm.streaming.IRKeyWordStreaminThread.run(IRKeyWordStreaminThread.java:119)
我的插入代码
Transaction tx = null; Session session = sessionFactory.openSession(); tx = session.beginTransaction(); int count = 0; try { for (Iterator itrList = statusToInsert.iterator(); itrList.hasNext();) { try { IRecord record = (IRecord) itrList.next(); session.save(record); count++; if ( count % 10 == 0 ) { session.flush(); session.clear(); tx.commit(); tx = session.beginTransaction(); } } catch (Exception e) { tx.commit(); session.close(); session = sessionFactory.openSession(); tx = session.beginTransaction(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); log.error(sw.toString()); } finally { tx.commit(); session.close(); }
问候,
罗希特
问题是您的代码正在处理异常,这在99.9%的情况下是一件很不好的事情,并且正在发生以下情况:
与会话的交互之一在try块中失败,并引发异常。发生这种情况时,会话将处于无效状态,因为它处于不一致状态,因此不能用于 绝对任何内容 。但是您的代码与catch块中的会话进行交互,从而触发断言。
在会话发生异常之后,唯一安全的事情是回滚事务并关闭它。任何其他类型的交互都可能会生成另一个异常(在这种情况下为断言异常)。