62,614
社区成员
发帖
与我相关
我的任务
分享
public void a() {
con.setAutoCommit;
dao.a();
b(); // 调用 b 方法
dao.a();
con.commit;
}
public void b() {
con.setAutoCommit;
dao.b();
dao.b();
con.commit;
}
public void c() {
con.setAutoCommit;
dao.c();
dao.c();
con.commit;
}
public void facade1() {
con.begin
service.a();
service.b();
facade2(); // 调用 facade2 方法
con.commit;
}
public void facade2() {
con.begin
service.e();
service.f();
con.commit;
}
Connection con = null;
ConnectionManager manager = ConnectionManager.getInstance();
try {
con = manager.getConnection();
con.setAutoCommit(false);
chain.doFilter(request, response);
con.commit;
}catch(Exception e) {
con.rollback;
}finally{
if(con!=null) {
con.close();
}
manager.removeConnection();
}
Connection con = null;
ConnectionManager manager = ConnectionManager.getInstance();
try {
con = manager.getConnection();
con.setAutoCommit(false);
service1.s1();
service2.s2();
service3.s3();
con.commit;
}catch(Exception e) {
con.rollback;
}finally{
if(con!=null) {
con.close();
}
manager.removeConnection();
}
public ConnectionManager {
private static ThreadLocal<Connection> cons = new ThreadLocal<Connection>();
private static ConnectionManger manger = new ConnectionManager();
private ConnectionManger() {
}
// 不使用单例的话,把下面的这些方法改成静态的也行
public static ConnectionManager getInstance() {
return manager;
}
public Connection getConnection() throws SQLException {
Connection con = cons.get();
if(con == null) {
// 从 ConnectionFactory 中获得一个连接
con = ConnectionFactory.getConnection();
setConnection(con);
}
return con;
}
public void removeConnection() {
cons.remove();
}
private void setConnection(Connection con) {
cons.set(con);
}
}
Connection con = null;
PreparedStatement ps = null;
try {
con = ConnectionManager.getConnection();
ps = con.prepared....;
ps.execute(....);
}catch(SQLException e) {
throw new WrapperSQLException(e);
}finally {
if(ps != null) {
try {
ps.close();
}catch(SQLException e) {
throw new WrapperSQLException(e);
}
}
// 这里的 con 不能关
}