DBHelper

public class DBHelper {
	
	public static DataSource ds = JNDIDataSource.getDS();
	public static ThreadLocal<Connection> container = new ThreadLocal<Connection>();
	
	public static ThreadLocal<Connection> getContainer(){
		return container;
	}
	
	public static DataSource getDataSource(){
		return ds;
	}
	
	public static void startTransaction(){
		Connection conn = container.get();
		if(conn==null){
			conn = getConnection();
			container.set(conn);
		}
		try{
			conn.setAutoCommit(false);
		}catch(SQLException e){
			throw new RuntimeException(e.getMessage(),e);
		}
	}
	public static void commit(){
		Connection conn = container.get();
		if(conn!=null){
			try{
				conn.commit();
			}catch (SQLException e) {
				throw new RuntimeException(e.getMessage(),e);
			}
		}
	}
	public static void rollback(){
		Connection conn = container.get();
		if(conn!=null){
			try{
				conn.rollback();
			}catch(SQLException e){
				throw new RuntimeException(e.getMessage(),e);
			}
		}
	}
	
	public static void close(){
		Connection conn = container.get();
		if(conn!=null){
			try{
				conn.close();
			}catch(SQLException e){
				
			}finally{
				container.remove();
			}
		}
	}
	public static Connection getConnection(){
		try{
			return ds.getConnection();
		}catch(Exception e){
			throw new RuntimeException();
		}
	}
	public static QueryRunner getQueryRunner(){
		QueryRunner qr = new QueryRunner(ds);
		return qr;
	}
	

}
相關文章
相關標籤/搜索