Spring中JdbcTemplate实现

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);
	}
	
	

}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值