我有一个像这样结构的项目
业务逻辑层 - >> DAO层 - >> QueryExecuter
Business Object调用dao layer和dao层,然后调用QueryExecuter类来执行查询。 QueryExecuter类如下
public class QueryExecutor {
private static final Logger LOG = Logger.getLogger(QueryExecutor.class);
//java.sql.Connection
private Connection connection;
public QueryExecutor(){
//apache commons db utils QueryRunner object.
queryRunner = new QueryRunner( );
initilizeConnection();
}
private QueryRunner queryRunner;
private QueryResult queryResult = new QueryResult();
private void initilizeConnection(){
LOG.info("Getting Connection ");
try {
this.connection = FitClineConnectionManager.getInstance().getConnection();
} catch (SQLException e) {
LOG.fatal("Problem Getting connection ");
LOG.fatal(e.getMessage());
} catch (IOException e) {
LOG.fatal("Problem Getting connection ");
LOG.fatal(e.getMessage());
} catch (PropertyVetoException e) {
LOG.fatal("Problem Getting connection ");
LOG.fatal(e.getMessage());
}
}
public QueryResult saveAndReturnId(String sql , Object[] params ) {
ResultSet rs = null;
Connection connection = null;
PreparedStatement statement = null;
try {
connection = getConnection();
statement = connection.prepareStatement(sql , Statement.RETURN_GENERATED_KEYS);
queryRunner.fillStatement( statement, params);
statement.executeUpdate();
rs = statement.getGeneratedKeys();
queryResult.setLastInsertedId( new AutoGeneratedKeyHandler().handle( rs ) );
queryResult.setStatus( QUERY_STATUS.SUCCESS.getCode() );
} catch (SQLException e) {
if ( e.getSQLState().equalsIgnoreCase("23000") ){
queryResult.setError( ErrorCodeProperties.getInstance().get_00004() );
}
LOG.error(e.getMessage());
} finally{
if ( statement != null ){
try {
//closing statement
DbUtils.close( statement );
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
closeConnection();
}
return queryResult;
}
}
在此结构中,连接在QueryExecuter类中进行管理,如何从Business Layer打开事务b / c连接在QueryExecuter类中进行管理。我希望我的业务层中的连接对象能够这样做。有没有聪明的方法来实现这一目标。 我没有在我的项目中使用任何依赖注入,只是apache公共DBUtils和jdbc。
P.S。在当前场景中,QueryExecuter对象是在基类Dao类中组成的,因此多个方法调用(用于事务)将导致从池中获取多个连接。