Spring EntityManager Hibernate 异常处理
在 Spring、JPA、Hibernate 项目中,我试图让异常处理正常工作。对于以下代码:
@Repository("mscoutService")
public class MScoutServiceImpl implements MScoutService, Serializable {
@PersistenceContext
private EntityManager em;
...
@Override
@Transactional
public void deleteMission(Long missionId) {
try {
Mission mis = em.find(Mission.class, missionId);
em.remove(mis);
} catch (Exception e) {
handle_exception();
}
}
我试图捕获底层的 hibernate/jdbc/db 异常(例如,当依赖实体仍然存在时,删除将失败并出现 org.springframework.orm.hibernate3.HibernateJdbcException)并执行一些操作。但是,永远不会到达捕获代码(在调试器中检查)。
我想这与 Spring 管理此问题的方式有关,但我不知道如何在 em.remove() 期间捕获异常...
任何帮助都会受到赞赏!
In a Spring, JPA, Hibernate project I'm trying to get exception handling working. For the following code:
@Repository("mscoutService")
public class MScoutServiceImpl implements MScoutService, Serializable {
@PersistenceContext
private EntityManager em;
...
@Override
@Transactional
public void deleteMission(Long missionId) {
try {
Mission mis = em.find(Mission.class, missionId);
em.remove(mis);
} catch (Exception e) {
handle_exception();
}
}
I'm trying to catch underlying hibernate/jdbc/db exceptions (for example when dependent entities are still present the remove will fail with a org.springframework.orm.hibernate3.HibernateJdbcException) and perform some actions. However the catch code is never reached (checked in the debugger).
I guess this has to do with the way Spring manages this, but I don't know just how I can catch exceptions during em.remove()...
Any help is appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为会话刷新时会发生异常。也许当事务提交时它会被刷新 - 即通过 spring 代理。如果您想手动刷新,可以使用
entityManager.flush()
。This is because the exception occurs when the session gets flushed. And perhaps it gets flushed when the transaction is committed - i.e. by the spring proxy. If you want to manually flush, you can use
entityManager.flush()
.