如果我的childClass方法getInfoFromDB()和saveToDB()需要做不同的逻辑,我可以知道如何创建childClass吗?
public abstract class BaseClass {
public abstract Object doTransaction();
public Object executeTrans() {
//do something
tx.begin();
this.doTransaction();
tx.commit();
}
}
public childClass extends BaseClass{
@Override
public Object doTransaction(){
//overide to get something from database so can only be used for getInfoFromDB() and not for saveToDB()
return something;
}
public List<String> getInfoFromDB(){
super.executeTrans();
}
public void saveToDB(){
super.executeTrans() ;
}
}发布于 2009-08-14 08:37:42
在这种情况下,您应该使用模板模式,如下所示:
public abstract class BaseClass
{
public Object executeTrans(Template template)
{
tx.begin();
template.doTransaction();
tx.commit();
}
}
public interface Template
{
public void doTransaction();
}
public childClass extends BaseClass
{
public List<String> getInfoFromDB()
{
executeTrans(
new Template()
{
public void doTransaction()
{
...do get info from DB here.
}
}
);
}
public void saveToDB()
{
executeTrans(
new Template()
{
public void doTransaction()
{
...do save to DB here.
}
}
);
}
}也就是说,我建议使用Spring JDBC模板类,而不是使用您自己的模板类-它们已经被尝试和测试过了,并且已经解决了您在使用嵌套事务时会遇到的问题。
发布于 2009-08-14 08:41:32
将包含不同逻辑的Runnable传递给executeTrans()方法。
但是,我不确定模板方法模式是否真的是您在这里需要的(以及它是如何处理回滚的?)。您可能希望研究一下允许declarative transactions的框架,比如Spring。
发布于 2009-08-14 09:08:57
尼克,我要使用的"tx“看起来像下面这样。从代码判断,最佳实践是生命周期是正常的,因为它由savetodb()和getinfofromdb()调用
public abstract class BaseClass
{
public Object executeTrans(Template template)
{
// PersistenceManager pm = ...;
Transaction tx = pm.currentTransaction();
try {
tx.begin();
template.doTransaction();
tx.commit();
} finally {
if (tx.isActive()) {
tx.rollback();
}
}
}
}https://stackoverflow.com/questions/1276624
复制相似问题