2012-07-21 67 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,你仍然可以使用相同的基本模板方法模式。只是谷歌的「模板方法」。有很多關於它的文章。