package com.powernode.spring6.test; import com.powernode.spring6.bean.User; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementCallback; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Test { @org.junit.Test public void TestCallBack() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); //如果想写JDBC代码,可以用callback回调函数 JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class); //准备SQL语句 String sql = "select id,real_name,age from users where id = ?"; //注册回调函数,当execute方法执行的时候,回调函数的doInPreparedStatement方法会被执行 User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() { @Override public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException { ps.setInt(1, 3); ResultSet resultSet = ps.executeQuery(); User user = new User(); while (resultSet.next()) { user.setId(resultSet.getInt("id")); user.setRealName(resultSet.getString("real_name")); ; user.setAge(resultSet.getInt("age")); } return user; } }); System.out.println(user); } }
package com.powernode.spring6.test;
import com.powernode.spring6.bean.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test
{
@org.junit.Test
public void TestCallBack()
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//如果想写JDBC代码,可以用callback回调函数
JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
//准备SQL语句
String sql = "select id,real_name,age from users where id = ?";
//注册回调函数,当execute方法执行的时候,回调函数的doInPreparedStatement方法会被执行
User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {
@Override
public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
ps.setInt(1, 3);
ResultSet resultSet = ps.executeQuery();
User user = new User();
while (resultSet.next()) {
user.setId(resultSet.getInt("id"));
user.setRealName(resultSet.getString("real_name"));
;
user.setAge(resultSet.getInt("age"));
}
return user;
}
});
System.out.println(user);
}
}