Spring框架在实现JdbcTemplate的时候,除了使用模板方法之外,还引入了相应的Callback接口定义外,以避免每次使用该Helper类的时候都需要进行子类化。
StatementCallback.java
package com.binzi;
import java.sql.SQLException;
import java.sql.Statement;
public interface StatementCallback {
Object doWithStatement(Statement stmt) throws SQLException;
String doWithUser(User user);
}
JdbcTemplate.java
package com.binzi;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTemplate {
public final Object execute(StatementCallback callback){
Connection con=null;
Statement stmt=null;
try{
con=getConnection();
stmt=con.createStatement();
Object retValue=callback.doWithStatement(stmt);
return retValue;
}
catch (SQLException e) {
// TODO: handle exception
}
finally{
}
return callback;
}
private Connection getConnection() {
// TODO Auto-generated method stub
return null;
}
public final String doWithUser(StatementCallback callback){
User user=new User();
user.setUserName("test");
String stringNew="";
stringNew=callback.doWithUser(user);
return stringNew;
}
}
User.java
package com.binzi;
public class User {
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String realUserName(){
return userName+"Manager";
}
}
Test.java
package com.binzi;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JdbcTemplate jdbcTemplate=new JdbcTemplate();
final String str="test";
final String sql="update ...";
StatementCallback callback=new StatementCallback() {
@Override
public String doWithUser(User user) {
// TODO Auto-generated method stub
String testString="";
user.setPassword("22");
testString="真实名称"+user.realUserName()+";用户密码"+user.getPassword();
System.out.println(testString);
return testString;
}
@Override
public Object doWithStatement(Statement stmt) throws SQLException {
// TODO Auto-generated method stub
return new Integer(stmt.executeUpdate(sql));
}
};
jdbcTemplate.doWithUser(callback);
}
}