日期:2014-05-16  浏览次数:20632 次

使用Spring的SimpleJdbcTemplate完成DAO操作

l???????SimpleJdbcTemplate内部包含了一个NamedParameterJdbcTemplate;所以NamedParameterJdbcTemplate能做的事情SimpleJdbcTemplate都能干,SimpleJdbcTemplate相对于NamedParameterJdbcTemplate主要增加了JDK5.0的泛型和可变长度参数支持。
l???????public?<T>?List<T>?query(String?sql,?ParameterizedRowMapper<T>?rm,?Object...?args)
l???????public?<T>?T?queryForObject(String?sql,?ParameterizedRowMapper<T>?rm,?SqlParameterSource?args)
l???????public?<T>?List<T>?query(String?sql,?ParameterizedRowMapper<T>?rm,?SqlParameterSource?args)
l???????getJdbcOperations返回的是JdbcOperations(实现JdbcTemplate)
l???????getNamedParameterJdbcOperations返回的是NamedParameterJdbcOperations(实现是NamedParameterJdbcTemplate)

实例说明:
public?class?StuDaoImple?implements?StuDaointer?{
????private?SimpleJdbcTemplate?simplejdbctemp;
????public?StuDaoImple(){
???????simplejdbctemp=new?SimpleJdbcTemplate(SQLConnUtil.getDataSource());
????}//?SQLConnUtil为JDBC工具类,提供了得到数据源的静态方法
????/*
?????*?可以通过SimpleJdbcTemplate得到NamedParameterJdbcTemplate或JdbcTemplate
?????*/
????public?void?AddStu(Stu?stu){
???????String?sql="insert?into?stu?values(:sname,:ssex,:sbrith)";
???????SqlParameterSource?ps=new?BeanPropertySqlParameterSource(stu);
???????KeyHolder?key=new?GeneratedKeyHolder();
???????this.simplejdbctemp.getNamedParameterJdbcOperations().update(sql,?ps,?key);
???????System.out.println(key.getKey().intValue());
????}
????/*?SimpleJdbcTemplate的第一个好处:
?????*?SimpleJdbcTemplate的update方法中参数是动态的,但是只能用?代替参数
?????*/
????public?void?DelStu(int?id){
???????String?sql="delete?stu?where?s_id=?";
???????simplejdbctemp.update(sql,?id);
????}
????/*
?????*?SimpleJdbcTemplate的update方法中参数是动态的,它的个数是动态的
?????*/
????public?void?UpdStu(Stu?stu){
???????String?sql="update?stu?set?s_name=?,s_sex=?,s_brith=??where?s_id=?";
???????simplejdbctemp.update(sql,?stu.getSname(),stu.getSsex(),stu.getSbrith(),stu.getSid());
????}
????/*
?????*?SimpleJdbcTemplate的第二个好处:
?????*?SimpleJdbcTemplate的queryForObject方法可以直接返回Stu对象,不用转换
?????*/
????public?Stu?getone(int?id){
???????String?sql="select?s_id?as?sid,s_name?as?sname,s_sex?as?ssex,s_brith?as?sbrith?from?stu?where?s_id=?";
???????Stu?stu=simplejdbctemp.queryForObject(sql,?ParameterizedBeanPropertyRowMapper.newInstance(Stu.class),?id);
???????return?stu;
????}
????public?List?getall(){
???????String?sql="select?s_id?as?sid,s_name?as?sname,s_sex?as?ssex,s_brith?as?sbrith?from?stu";
???????List?list=simplejdbctemp.getJdbcOperations().query(sql,?new?BeanPropertyRowMapper(Stu.class));
???????return?list;
????}
}