在上2个例子中,参数的设置必须要与sql语句中的?
对应,当参数很多时就会很不方便。
package cn.itcast.jdbc.spring;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import cn.itcast.domain.User;
import cn.itcast.jdbc.JdbcUtils;
public class NamedJdbcTemplate {
public static void main(String[] args) {
User user = new User();
user.setMoney(10);
user.setId(2);
System.out.println(findUser(user));
}
static NamedParameterJdbcTemplate named = new NamedParameterJdbcTemplate(
JdbcUtils.getDataSource());
static int addUser(User user){
String sql="insert into user(name,birthday,money)values(:name,:birthday,:money)";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user); //参数源
KeyHolder keyHolder=new GeneratedKeyHolder();
named.update(sql, ps,keyHolder);
int id=keyHolder.getKey().intValue();
user.setId(id);
return id;
}
static User findUser(User user) {
String sql = "select id ,name,money,birthday from user where money > :money and id<:id";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user); //参数源
Object u = named.queryForObject(sql, ps,
new BeanPropertyRowMapper<User>(User.class));
return (User) u;
}
}
上面的例子中使用了BeanPropertySqlParameterSource
参数源,这要求sql语句中的命名参数必须与user中的参数同名。