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