public class SoftwareTest extends UnitTest {
@Before
public void setup() {
Fixtures.deleteAll(); // will fail if comment that. why?????
}
@Test
public void createSoftwareWithNullAuthor() {
// when author is null
Author nullAuthor = null;
Software software = new Software("software1", "description1", nullAuthor);
try {
software.save();
fail("author should not be null");
} catch (PersistenceException ex) {
}
}
@Test
public void createSoftwareWithOkAuthor() {
// when author is ok
Author okAuthor = new Author("author1", "email1").save(); // ERROR HERE!
Software software2 = new Software("software2", "description2", okAuthor);
Software savedSoftware = software2.save();
assertNotNull(savedSoftware);
assertEquals(savedSoftware, software2);
assertNotNull(savedSoftware.author);
assertEquals(okAuthor, savedSoftware.author);
}
}
当用Fixtures.deleteAll()
取消注释该行时,我们将在第二种方法中获得异常 - 当save()
为作者时为createSoftwareWithOkAuthor()
。 为什么会这样?save方法 - 在发生异常后不刷新会话
org.hibernate.AssertionFailure: null id in models.Software entry (don't flush the Session after an exception occurs)
at org.hibernate.event.def.DefaultFlushEntityEventListener.checkId(DefaultFlushEntityEventListener.java:82)
at org.hibernate.event.def.DefaultFlushEntityEventListener.getValues(DefaultFlushEntityEventListener.java:190)
at org.hibernate.event.def.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:147)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:240)
at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:99)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206)
是的。这有效,但我也尝试过。但还有另一个问题:在@Before setup()方法中我有Fixtures.deleteAll();如果我评论这条线,那么我会在第二个(分割)方法中出现同样的错误。这里:作者okAuthor = new Author(“author1”,“email1”)。save(); – ses 2011-03-15 08:42:04
我修改了我的问题 – ses 2011-03-15 09:00:51
我们如何阻止会话不会失效? – 2014-03-06 13:23:29