Service层调用DAO层方法。
由于一个Service方法可能需要调用多个DAO对象的方法,需要在Service层进行事务控制。
由于一些原因,需要采用编程式事务(现使用TransactionTemplate)。
可是存在一个问题:
只有当创建TransactionTemplate对象的DataSourceTransactionManager使用的DataSource对象和DAO对象创建JdbcTemplate对象使用的DataSource是同一个对象时才能在transactionTemplate.execute()方法中控制事务。暂时想到如下设计:
1. BasicDao类
所有DAO的父类,提供静态变量DataSource用于为所有的DAO类创建JdbcTemplate对象。
同时提供DataSource的get方法,用于在Service方法中创建DataSourceTransactionManager对象。
public class BasicDao { private static DataSource dataSource; protected JdbcTemplate jdbc; static { dataSource = new MyDataSource(); } public BasicDao() { jdbc = new JdbcTemplate(dataSource); } //....getters and setters } 2. DAO类
继承自BasicDao类,完成数据库操作。
3. Service类
调用DAO类的方法,完成业务。
DataSource dataSource = BasicDao.getDataSource(); DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource); TransactionTemplate txTemplate = new TransactionTemplate(txManager ); final Dao1 dao1= new Dao1(); final Dao2 dao2= new Dao2(); transactionTemplate.execute(new TransactionCallback(){ public Object doInTransaction(TransactionStatus arg0) { dao1.function1(); dao2.function2(); //.... return null; } }); 暂时只能这样来实现,请问各位有什么更好的实现吗?不要使用Spring的IOC容器和声明式事务。
以上面的Service方法为例吧:
1.在ProxyClass中进行事务的控制,将DataSource保存到ThreadLocal。
2.在ProxyClass中调用代理的具体Service类的service方法。
3.Service类的service方法只完成具体的业务dao方法调用。
4.Dao类的DataSource对象从ThreadLoacl中取得。
public class ProxyClass { public static final ThreadLocal threadLocal = new ThreadLocal(); private DataSourceTransactionManager txManager; private TransactionTemplate txTemplate; TargetService target; //代理的具体的目标服务对象 public ProxyClass() { DataSource dataSource = new MyDataSource(); txManager = new DataSourceTransactionManager(dataSource); txTemplate = new TransactionTemplate(txManager ); threadLocal.set(dataSource); } public void service() { transactionTemplate.execute(new TransactionCallback(){ public Object doInTransaction(TransactionStatus arg0) { target.service(); //调用具体服务方法 } }); } //...... } 问题补充:finallygo 写道不对的,你的代码编译可以通过吗?
如果是直接使用JDBC进行操作的话,在ThreadLocal应该存储Connection。