问题描述
因此,我正在进行这种通用的DAO操作,从表面上看,这似乎还可以。它基本上是基于Hibernate的CaveatEmptor示例应用程序建模的。
So I've got this generic DAO thing going on and at face value it appears to be ok. It's basically modeled after the CaveatEmptor sample application from the Hibernate guys.
最重要的是,我有一个业务层...应用程序的实质。完全不知道任何特定的DAO实施。
On top of that I have a business layer...the guts of the application. It's completely unaware of any specific DAO implementation.
直到我开始考虑交易之前,到目前为止的一切似乎都还不错。如果将交易留给客户来实施,那么我该如何保持各层之间的良好隔离呢?就是说,我现在正在使用Hibernate,我真的感觉不很像在我的业务层代码中添加特定于Hibernate的事务。
Everything up to this point seems fine, until I start thinking about transactions. If transactions are left to the client to implement, then how in the world do I maintain the nice separation I've got going on between my layers? That is, I'm using Hibernate at the moment, and I don't really feel much like adding hibernate-specific transactions to my business layer code.
我可以创建一个具有begin,commit和rollback方法的简单事务接口,并将实现传递给我的业务层...但是...我不确定...
I could create a simple transaction interface with begin, commit, and rollback methods and pass an implementation to my business layer...but...I'm not sure...
这就是挑战:您能为我推荐一种无需使用Spring(或EJB,或任何其他框架)一词的方法吗?
推荐答案
我记得的建议在业务层控制事务,因为事务是业务问题。 (如果您设计BankAccount类,则事务是域语言的一部分。)
I remember that Martin Fowler advices to keep the control of the transaction in the business layer because transaction is a business problem. (If you design a BankAccount class, a transaction is part of the domain language).
您可以尝试在.NET中实现TransactionScope,就像它那样工作
You can try to implement a TransactionScope as in .NET it works something like that
using (TransactionScope ts = new TransactionScope())
{
...
}
这是同一件事(不完全是,但如果您是Java专家,则对您来说更明确)
It's the same thing as (not exactly but if you are a Java guy, it's more explicit to you)
TransactionScope scope = new TransactionScope();
try
{
...
scope.Commit();
}
catch(Exception ex)
{
scope.Rollback();
throw;
}
要使您的业务层与任何DAO技术脱钩,您可以在自己的服务器上添加TransactionFactory域语言,该语言返回您使用Commit和Rollback方法定义的ITransactionScope(接口)。这样,您的域层就不会绑定到DAO层,只有TransactionFactory的一个具体实现。
To decouple your business layer from any DAO technologies you can add a TransactionFactory in your domain language, which return a ITransactionScope (an interface) that you have defined with a Commit and Rollback methods. This way your domain layer is not bound to your DAO layer, only a concrete implementation of TransactionFactory is.
ITransactionScope scope = transactionFactory.CreateTransaction();
try
{
...
scope.Commit();
}
catch(Exception ex)
{
scope.Rollback();
throw;
}
这篇关于DAO模式-交易适合什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!