TS-*_*TS- 1 java hibernate spring-3
我一直在寻找这个问题,在StackOverflow和Google上有很多这样的问题,但我似乎无法为我工作.
这是我的代码Spring配置:(我不使用任何切入点 - 我想我不需要?)
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
...
</bean>
<bean id="hibernateSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
...
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
Run Code Online (Sandbox Code Playgroud)
我有一个服务类:
@Service
public class ServiceImpl implements ServiceInterface
{
/**
* Injected session factory
*/
@Autowired(required=true)
private SessionFactory sessionFactory;
@Autowired(required=true)
private Dao myDao;
/**
* {@inheritDoc}
*/
@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
public void scheduleBlast(BlastParameters blastParameters) throws ServiceException
{
... do bunch of stuff ..
myDao.persist(entity)
if(true)
throw new ServiceException("random error")
}
.. setter methods and other stuff ..
}
Run Code Online (Sandbox Code Playgroud)
和Dao类:
public class DaoImpl implements DaoInterface
{
@Autowired(required=true)
private SessionFactory sessionFactory
/**
* {@inheritDoc}
*/
@Transactional(propagation=Propagation.MANDATORY)
public void persist(Entity e) throws DaoException
{
try
{
sessionFactory.getCurrentSession().persist(e);
}
catch(Exception ex)
{
throw new DaoException(ex);
}
}
.. setter methods and other stuff ..
}
Run Code Online (Sandbox Code Playgroud)
消除了一些不必要的细节(例如,缺少setter等),假设代码完全正常.
我上面的问题是,当我添加throw随机异常行时,它不会回滚,通过DAO持久保存的对象会保留在db中.
我使用的是Spring 3.1和Hibernate 3.6(因为Spring 3.1上有一个Hibernate 4.0的bug)
思考?
谢谢
Rav*_*wal 11
这是事务管理的预期行为.@Transactional的默认行为是仅针对运行时异常进行回滚.如果你希望你的东西在抛出DaoException之后回滚,那么将它添加到回滚例外列表中.不要忘记还包括RuntimeException.在Dao类上尝试以下内容@Transactional(propagation = Propagation.Mandatory,rollbackFor = {RuntimeException.class,DaoException.class})
TS-*_*TS- 11
我找到了问题的原因以及为什么交易(貌似)管理得不好.
在我的代码中的某个地方
/**
* {@inheritDoc}
*/
@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
public void doWork(Parameters param) throws ServiceException
{
... do bunch of stuff ..
myDao1.persist(entity)
-- Some logic here --
... do bunch of stuff ..
myDao2.persist(entity2)
if(true)
throw new ServiceException("random error")
}
Run Code Online (Sandbox Code Playgroud)
它所说的" - 这里有一些逻辑 - "的部分,有一些使用原始SQL并调用执行更新的逻辑:
Query query = sessionFactory.getCurrentSession().createSQLQuery(queryText);
query.executeUpdate();
Run Code Online (Sandbox Code Playgroud)
并且因为它没有使用Hibernate查询,而是使用原始SQL执行,它导致调用flush,因此在调用之前完成的任何工作都将与它一起提交.
我重新编写逻辑流程来解释这个逻辑,以确保正确管理事务.虽然使用原始SQL可能表明存在错误 - 由于服务试图完成的事情和提高服务性能,这是必须要做的事情.
| 归档时间: |
|
| 查看次数: |
21245 次 |
| 最近记录: |