gpt4 book ai didi

java - 事务内部的 Spring DAO 异常翻译

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:19 27 4
gpt4 key购买 nike

我正在使用 Spring 3.1.2Hibernate 4

我有一个用 @Repository 注释的 DAO 实现类 MyDaoImpl 以便启用异常转换。我有一个用 @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 添加到测试类中,以便我可以访问当前 session 以进行刷新。

一些额外的解释:在这种情况下,我在刷新 session (在事务内)时得到异常。我刷新 session 以避免误报,如文档中所述。此外,由于默认传播是必需的,testCreateA() 事务也用于调用 createA(),因此更改不会(通常)刷新,直到 testCreateA() 返回。

最佳答案

您是否添加了 PersistenceExceptionTranslationPostProcessor bean 定义?喜欢

   <!--
Post-processor to perform exception translation on @Repository classes
(from native exceptions such as JPA PersistenceExceptions to
Spring's DataAccessException hierarchy).
-->
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

来自 Spring doc .

Bean post-processor that automatically applies persistence exception translation to any bean that carries the @Repository annotation, adding a corresponding PersistenceExceptionTranslationAdvisor to the exposed proxy (either an existing AOP proxy or a newly generated proxy that implements all of the target's interfaces).

Translates native resource exceptions to Spring's DataAccessException hierarchy. Autodetects beans that implement the PersistenceExceptionTranslator interface, which are subsequently asked to translate candidate exceptions

关于java - 事务内部的 Spring DAO 异常翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12140644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com