2012-07-21 74 views
1

我们通常用连接池打交道时有以下代码:Java的锅炉板代码:连接管理

connection c = pool.borrow(); 
try { 
    business-logic-using-connection(c); 
} 
catch(connectionException e) { 
    connectionBad = true; 
} 
finally{ 
    if (connectionBad) { 
     pool.evict(c); 
    } else { 
     pool.return(c); 
    } 
} 

的问题是如何使这个锅炉板代码简单,比如一个可以这样做:

getConnectionAndDoWork(pool, business-logic-code) 

其中人们可以插入他们的业务逻辑,而不必重复相同的连接管理遍布各地的代码。一种方法是创建一个业务逻辑代码接口,如doWorkWithConnection,它需要连接并做一些工作。但是,这限制了业务逻辑代码应返回的内容;

有没有更好的方法来做到这一点在Java?

回答

2

使用回调模式,如Spring用于programmatic transaction management

interface PooledConnectionCallback<T> { 
    T doWithConnection(Connection c); 
} 

Pool pool = new Pool(poolParams); 
Integer returnedValue = pool.execute(
    new PooledConnectionCallback<Integer>() { 
    public Integer doWithConnection(Connection c) { 
     int someReturnValue = businessLogicUsingConnection(c); 
     return someReturnValue; 
    }}); 

Pool#execute方法,你可以有你需要处理异常和清理的样板代码。

+0

这是一个很好的方法来做到这一点。 – 2012-07-21 06:16:37

+0

什么是池#执行签名? – 2012-07-21 06:25:00

+0

' T Pool#execute(PooledConnectionCallback )' – 2012-07-21 06:26:03

0

如果您正在使用Spring,可以考虑使用JdbcTemplate或者在是NamedParameterJdbcTemplate:

http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html

http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.html

即使你不使用Spring,你仍然可以使用相同的基本模板方法模式。只是谷歌的“模板方法”。有很多关于它的文章。