package cn.liurui.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* @author lijun
* @date 2019/8/12 14:27
* 管理连接的工具类 用来实现连接 和线程的绑定
*/
@Component
public class ConnectionUtil {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
@Autowired
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
this.dataSource=dataSource;
}
// 获取当前线程的绑定连接
public Connection getThreadConnection(){
try {
Connection conn = tl.get();
if(conn==null){
conn = dataSource.getConnection();
tl.set(conn);
}
return tl.get();
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public void remove(){
tl.remove();
}
}