Spring中JdbcTemplate实现

来源:互联网 发布:arena仿真软件下载 编辑:程序博客网 时间:2024/06/05 04:02
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 stubreturn 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 stubJdbcTemplate jdbcTemplate=new JdbcTemplate();final String str="test";final String sql="update ...";StatementCallback callback=new StatementCallback() {@Overridepublic String doWithUser(User user) {// TODO Auto-generated method stubString testString="";user.setPassword("22");testString="真实名称"+user.realUserName()+";用户密码"+user.getPassword();System.out.println(testString);return testString;}@Overridepublic Object doWithStatement(Statement stmt) throws SQLException {// TODO Auto-generated method stubreturn new Integer(stmt.executeUpdate(sql));}};jdbcTemplate.doWithUser(callback);}}


 

原创粉丝点击