1. 建立一个工具类 用于从数据库中获取一个连接 并且实现线程绑定
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getThreadConnection() {
Connection connection = tl.get();
try {
if (connection == null) {
//从线程中获取一个连接 并且和线程绑定
connection = dataSource.getConnection();
tl.set(connection);
}
return connection;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//把线程和连接解绑
public void removeConnection(){
tl.remove();
}
}
2. 事务控制类
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try{
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try{
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollBack(){
try{
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try{
connectionUtils.getThreadConnection().close();
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
}
3. 建立工厂对象 优化频繁的事务操作
**
* @author Devin
* @version 1.0
* @date 2019/7/21 18:04
*/
public class BeanFactory {
private IAccountService accountService;
private TransactionManager transactionManager;
public final void setTransactionManager(TransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setAccountService(IAccountService accountService) {
this.accountService = accountService;
}
public IAccountService getAccountService() {
IAccountService iAccountService = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
try {
transactionManager.beginTransaction();
//执行操作
returnValue = method.invoke(accountService, args);
transactionManager.commit();
} catch (Exception e) {
transactionManager.rollBack();
e.printStackTrace();
} finally {
transactionManager.release();
}
return returnValue;
}
});
return iAccountService;
}
}