我正在使用Spring 3.1.2
和Hibernate 4
。交易中的Spring DAO異常翻譯
我有一個DAO實現類MyDaoImpl
註釋@Repository
,以便啓用異常轉換。我有@Transactional
註釋服務類MyService
如下:
public class MyService implements IMyService {
private MyDao myDao;
@Autowired
public void setMyDao(MyDao dao) {
this.myDao = dao;
}
@Override
@Transactional
public void createA(String name)
{
A newA = new A(name);
this.myDao.saveA(newA);
}
}
我已經寫了一個單元測試類MyServiceTest
如下:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:beans.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class MyServiceTest implements IMyServiceTest {
private IMyService myService;
private SessionFactory sessionFactory;
@Autowired
public void setMyService(IMyService myService)
{
this.myService = myService;
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
@Test
@Override
public void testCreateA()
{
//Assume that there is already a row of table A with the name "A1"
//so I expect to get a Spring DataAccessException (or subtypes)
//when the session is flushed
this.myService.createA("A1");
this.sessionFactory.getCurrentSession().flush();
//asserts
}
}
當我運行測試,我得到一個Hibernate特定的異常ConstraintViolationException
。我在論壇上發現這是因爲翻譯系統發生在交易之外,所以在這種情況下testCreateA()
返回後。我不知道這是否是真正的原因,但如果是這樣,這意味着我無法測試該翻譯適用於我的DAO。一種解決方案是從我的單元測試中刪除@Transactional
註釋,但我不會從回滾功能中受益。
您有哪些建議?
編輯:我已在我的上下文的測試類中聲明的SessionFactory
,讓我可以衝廁訪問當前會話。
一些額外的解釋:在這種情況下,當會話刷新時(這是在事務內部)我得到異常。我沖洗會議,以避免誤報,因爲它在文檔中解釋。另外,由於默認傳播是必需的,所以testCreateA()
交易也用於對createA()
的呼叫,所以這些更改不會刷新(通常),直到testCreateA()
返回。
我沒有看到這在doc http://static.springsource.org/spring/docs/3.1.x/彈簧框架參考/ HTML/dao.html。你確定它仍然是相關的嗎? –
@Mickael:AFAIK'@ Repository'指示異常轉換的類,'PersistenceExceptionTranslationPostProcessor'執行轉換任務。檢查我的編輯。 – xyz
我編輯了我的問題。添加後處理器並不能解決我的問題,我仍然在測試案例中得到一個Hibernate特定的異常。 –