Hibernate多级事务
我有一些休眠代码,我希望我的代码在 1 个事务中运行 让我用代码解释
public void changeBranch(Branch branch) throws DatabaseException {
//some code
humanDao.update(he);
superBranchUsername = branch.getFatherUsername();
int superBranchId = branchDao.getBranchIdByUserName(superBranchUsername);
BranchEntity superBranch = branchDao.load(superBranchId);
BranchEntity be = new BranchEntity();
setBranchEntity(be, he, pkId, bname, confirmed, level, studentCount, uname, superBranch);
branchDao.update(be); // update kardane jadvale Branch va Set kardane Human motenazer be on
//some code
}
一下 humanDao.update(he);
和 branchDao.update(be);
在 My GenericDAO 的事务句柄中运行, humanDao 和branchDao 都是从它继承的。 但我希望这段代码(上面写的)也能在事务中运行! 我怎样才能进入 Hibernate 来做到这一点?
I have some hibernate code and I want my code run in 1 transaction
let me explain in code
public void changeBranch(Branch branch) throws DatabaseException {
//some code
humanDao.update(he);
superBranchUsername = branch.getFatherUsername();
int superBranchId = branchDao.getBranchIdByUserName(superBranchUsername);
BranchEntity superBranch = branchDao.load(superBranchId);
BranchEntity be = new BranchEntity();
setBranchEntity(be, he, pkId, bname, confirmed, level, studentCount, uname, superBranch);
branchDao.update(be); // update kardane jadvale Branch va Set kardane Human motenazer be on
//some code
}
Both humanDao.update(he);
and branchDao.update(be);
run in transaction handle by My GenericDAO that humanDao and branchDao are inherited from it.
but I want this block of code (wrote above) to also run in a transaction!! How can I get to Hibernate to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DAO 不应该处理事务,其原因正是您所发现的:它们无法知道它们何时属于较大事务的一部分。
如果您使用 Spring 声明式事务,您将拥有一个服务层,可以为两者创建事务上下文DAO 并处理一切。 我建议做类似的事情。
更新:我添加了一个到 Spring 的链接。
DAOs should not handle transactions for exactly the reason you've discovered: they can't know when they're part of a larger transaction.
If you were using Spring declarative transactions, you'd have a service layer that would create the transaction context for both DAOs and deal with everything. I would recommend doing something like that.
UPDATE: I added a link to Spring.
请参阅:第 11 章. 事务和并发
Please see: Chapter 11. Transactions and Concurrency
我发现如果我在
changeBranch(Branchbranch)
中创建新会话并将此会话作为参数传递给我的 DAO,我应该如何修复它,我的问题就解决了I find how should I fix it if I new session in
changeBranch(Branch branch)
and pass this session as a parameter to my DAO my problem solved