现在搭建一个事务处理的类
代码如下
[code="java"]
private static final Log log = LogFactory.getLog(DBManager.class);
private static DataSource dataSource = null;
private static IConnMgr connMgr = null;
/**
* 管理连接
*/
public static final ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
/**
* 初始化数据源
*/
static {
try {
connMgr = DBCPConnMgr.getInstance();
connMgr.initDatabase();
dataSource = connMgr.getDataSource();
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
}
public static synchronized Connection getConnection(){
Connection conn = threadLocal.get();
try {
if (conn == null || conn.isClosed()) {
conn = dataSource.getConnection();
}
threadLocal.set(conn);
} catch (SQLException e) {
ExceptionUtil.printExceptionErr(e);
}
return conn;
}
/**
* 开启事务操作
*/
public static void beginTransaction() {
Connection conn = threadLocal.get();
try {
if (conn == null || conn.isClosed()) {
conn = dataSource.getConnection();
threadLocal.set(conn);
}
conn.setAutoCommit(false);
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
}
/**
* 提交事务操作
*/
public static void commit() {
Connection conn = threadLocal.get();
if (conn != null) {
try {
conn.commit();
conn.setAutoCommit(true);
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
}
}
/**
* 事务回滚操作
*/
public static void rollback() {
Connection conn = threadLocal.get();
if (conn != null) {
try {
if (log.isInfoEnabled()) {
log.info("++++ transaction rollback ++++");
}
conn.rollback();
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
}
}
/**
* 关闭事务
*/
public static void endTransaction() {
Connection conn = threadLocal.get();
if (conn != null) {
try {
if (log.isInfoEnabled()) {
log.info("++++ close transaction ++++");
}
conn.close();
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
}
}
[/code]
而在dao操作数据库的时候,我并没有在每个方法里面关闭连接,在service层中需要添加事务的时候
先开启事务-->提交事务-->关闭连接
这样一个步骤
但是如果一个service里用不上事务,就是简单的只有查询,插入,或者更新操作时,也这样在开头写上 开启事务,关闭事务
就多余了
但是不这样做,我又没办法关闭连接
因为你也不知道某一些方法在什么特定业务下就要进行控制事务
所以我的疑问是,在有事务控制的时候可以按我上述的类使用,但是在不使用事务的service中,我如何来控制连接关闭?
[code="java"]
@Override
public boolean queryRegisterHistoryBySerial(String serialText) {
boolean flag = false;
String sql = "SELECT * FROM registerLog WHERE serialText = ?";
ResultSetHandler rsh = new BeanHandler(RegisterLogEntity.class);
RegisterLogEntity entity = null;
Connection conn = null;
try {
conn = DBManager.getConnection();
entity = qRunner.query(conn, sql, rsh, serialText);
if (null != entity) {
flag = true;
}
} catch (Exception e) {
ExceptionUtil.printExceptionErr(e);
}
return flag;
}
[/code]
dao中其中的一个方法,并没有在最后控制conn.close();因为怕同一个service中其他的地方还应用到
有什么好的办法解决嘛?
我总共就18分,大家见谅一下,帮下忙