休眠保存、休眠回滚
我试图让我的 DAO 以这种方式工作:
public void incrementNumber(long id) throws Exception{
Session session = factory.openSession();
Number n = (Number)session.load(Number.class, id);
n.setNumber(n.getNumber() +5);
// throw new IllegalArgumentException("BLAH");
session.close();
}
- 通过注释掉异常,更新将提交。
- 通过取消注释(?)异常,它将回滚。
有什么办法可以实现这个目标吗?注意:事务部分是在服务中的事务注释下完成的。
I'm trying to make my DAO work this way:
public void incrementNumber(long id) throws Exception{
Session session = factory.openSession();
Number n = (Number)session.load(Number.class, id);
n.setNumber(n.getNumber() +5);
// throw new IllegalArgumentException("BLAH");
session.close();
}
- By commenting out the exception, the update will commit.
- By un-commenting(?) the exception, it will rollback.
Any way to achieve this? Note: the transaction part is done in a service, under a transactional annotation.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DAO主要负责持久化操作。它应该只提供CRUD和一些与特定实体相关的finder方法。
IMO,您的方法更像是业务操作而不是持久性操作。由于您有服务层,我建议您将此方法移至其中。
因此,您的 NumberDAO 可能如下所示:
而您的 NumberService 可能如下所示:
当您在服务层使用事务性注释时,如果您的服务方法成功返回,它将自动提交。如果在方法返回之前抛出任何异常,则事务会自动回滚。
DAO is mainly responsible for persistence operations .It should only provide CRUD and some finder methods relating to a particular entity.
IMO , your method more like a business operation rather than the persistence operations . As you have the service layer , I suggest you move this method to it.
So , your NumberDAO may look like this:
And you NumberService may look like this:
As you use transactional annotation in the service layer , it will commit automatically if your service method returns successfully .In case of any exceptions throw before the method returns , the transaction will rollback automatically .
提交并不总是提交到数据库,它在会话缓存中设置必须提交,然后当您执行刷新(也取决于配置)时,提交将转到数据库,或者当会话/事务时结束。
所以如果你想强制它在提交后使用flush()。
如果您可以在会话/交易关闭后等待检查。
commit is not always committing to the db, it is setting at the session cache that this has to be committed, then when you will do flush (also depending on the configuration) the commit will go to the DB, or when the session/transaction ends.
So if you want to force it use flush() after commit.
If you can wait check after the session/transaction is being closed.