Spring JdbcTemplate小结

jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))"); 
使用JdbcTemplate进行查询时,可以使用queryForXXX()等方法,例如使用queryForInt()方法传回user表格中的数据数目: jdbcTemplate.quertForInt("select count(*) from user"); 也可以使用queryForObject()传回一个查询后的对象,例如传回一个String对象: 
String name=(String)jdbcTemplate.queryForObject("selcet name from user where id=?",new Object[]{id},java.lang.String.class);) 
单独查询某个数据并赋值给特定对象时:

    public BaseObj getBaseObj(final int ID) { 
        String sql = "select * from " + DB_TABLE_NAME + " where NewsId=" + ID; 
        BaseObj obj =(BaseObj) getJdbcTemplate().query(sql,new ResultSetExtractor(){ 
            public Object extractData(ResultSet rs) throws SQLException,DataAccessException { 
                if (rs.next()) { 
                    NewsObj news = new NewsObj(); 
                    news.setID(rs.getInt("NewsID")); 
                    news.setTitle(rs.getString("NewsTitle")); 
                    news.setBigClass(rs.getInt("BigClassId")); 
                    news.setNewsContent(rs.getString("NewsContent")); 
                    news.setNewsKey(rs.getString("NewsKey")); 
                    news.setNewsAuthor(rs.getString("NewsAuthor")); 
                    news.setImg(rs.getBoolean("isImg")); 
                    news.setNewsFrom(rs.getString("NewsFrom")); 
                    return news; 
                } 
                return null; 
            } 
        }); 
       return obj;

    }

上面两个例子都是传回单独一笔数据,如果要传回多笔数据,则可以使用queryForList()方法

例如: 
List rows=jdbcTemplate().queryForList("select * from user where id="+id.intValue()); 传回的list中包括的是map对象,每个map对象代表查询结果中的一笔数据,每笔数据包括多个字段,要取得字段中的值,就要使用字段名作为key, 
例如: 
    Iterator it=rows.iterator(); 
    while(it.hasNext()){ 
        Map result=(Map)it.next(); 
        System.out.println(userMap.get("id")); 
        System.out.println(userMap.get("name")); 
        System.out.println(userMap.get("age")); 
     }

在查询的同时,你可以在返回结果之前先进行一些处理,这就要实现RowCallbackHandler接口

public User find(Integer id){ 
    final User user=new User(); 
    jdbcTemplate.query("select * from user where id=?",new Object[]{id}, 
                                     new RowCallBackHandler(){ 
                                           public void proccessRow(ResultSet rs){ 
                                                 user.setId(new Integer(rs.getInt("id"))); 
                                                 uset.setName(rs.getString("name"));    
                                            }}); 
    return user; 
}

如果一次要返回多个查询结果对象,则可以实现RowMapper接口

public class UserRowMapper implements RowMapper{ 
        public Object MapRow(ResultSet rsmint rowNum) throws SQLException{ 
                User user=new User(); 
                user.setId(new Integer(rs.getInt("id"))); 
                user.setName(rs.getString("name")); 
                return user; 
       } 
}

使用RowMapper查询单笔数据

public User find(Integer id){ 
         User user=(User)jdbcTemplate.queryForObject("select * from user where id=?",new Object[]{id},new UserRowMapper()); 
          return user; 
}

使用RowMapper查询多笔数据

class UserRowMapper implements RowMapper { 
         public Object mapRow(ResultSet rs,int index) throws SQLException 
         { 
             User u = new User(); 
             u.setId(rs.getString(”ID”)); 
             u.setName(rs.getString(”Name”)); 
             u.setPassword(rs.getString(”Password”)); 
             return u; 
         } 
     } 
public List select(String where) 
    { 
        List list;        
        String sql = "select * from admin "+where;        
        list = jdbcTemplate.query(sql,new RowMapperResultReader(new UserRowMapper())); 
        return list; 
    }

传回的users对象中,包括了从数据库查询出来的结果,并已经封装成user对象

JdbcTemplate语句使用:

1、使用JdbcTemplate的execute()方法执行SQL语句

代码 
jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");

2、如果是UPDATE或INSERT,可以用update()方法。

代码 
jdbcTemplate.update("INSERT INTO USER VALUES('"   
            + user.getId() + "', '"   
            + user.getName() + "', '"   
            + user.getSex() + "', '"   
            + user.getAge() + "')"); 

3、带参数的更新

代码 
jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?", new Object[] {name, id});

代码 
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()}); 

4、使用JdbcTemplate进行查询时,使用queryForXXX()等方法

代码 
int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");

代码 
String name = (String) jdbcTemplate.queryForObject("SELECT name FROM USER WHERE user_id = ?", new Object[] {id}, java.lang.String.class);

代码 
List rows = jdbcTemplate.queryForList("SELECT * FROM USER");

代码 
List rows = jdbcTemplate.queryForList("SELECT * FROM USER");    
Iterator it = rows.iterator();    
while(it.hasNext()) {    
    Map userMap = (Map) it.next();    
    System.out.print(userMap.get("user_id") + "\t");    
    System.out.print(userMap.get("name") + "\t");    
    System.out.print(userMap.get("sex") + "\t");    
    System.out.println(userMap.get("age") + "\t");    

JdbcTemplate将我们使用的JDBC的流程封装起来,包括了异常的捕捉、SQL的执行、查询结果的转换等等。spring大量使用Template Method模式来封装固定流程的动作,XXXTemplate等类别都是基于这种方式的实现。 
除了大量使用Template Method来封装一些底层的操作细节,spring也大量使用callback方式类回调相关类别的方法以提供JDBC相关类别的功能,使传统的JDBC的使用者也能清楚了解spring所提供的相关封装类别方法的使用。

JDBC的PreparedStatement

代码 
final String id = user.getId();    
final String name = user.getName();    
final String sex = user.getSex() + "";    
final int age = user.getAge();    
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",    
                     new PreparedStatementSetter() {    
                         public void setValues(PreparedStatement ps) throws SQLException {    
                             ps.setString(1, id);    
                             ps.setString(2, name);              
                             ps.setString(3, sex);    
                             ps.setInt(4, age);    
                         }    
                     });  

代码 
final User user = new User();    
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",    
                    new Object[] {id},    
                    new RowCallbackHandler() {    
                        public void processRow(ResultSet rs) throws SQLException {    
                            user.setId(rs.getString("user_id"));    
                            user.setName(rs.getString("name"));    
                            user.setSex(rs.getString("sex").charAt(0));    
                            user.setAge(rs.getInt("age"));    
                        }    
                    });  

代码 
class UserRowMapper implements RowMapper {    
    public Object mapRow(ResultSet rs, int index) throws SQLException {    
        User user = new User();    
        user.setId(rs.getString("user_id"));    
        user.setName(rs.getString("name"));    
        user.setSex(rs.getString("sex").charAt(0));    
        user.setAge(rs.getInt("age"));    
        return user;    
    }    
}    
public List findAllByRowMapperResultReader() {    
    String sql = "SELECT * FROM USER";    
    return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));    
}  

在getUser(id)里面使用UserRowMapper

代码 
public User getUser(final String id) throws DataAccessException {    
    String sql = "SELECT * FROM USER WHERE user_id=?";    
    final Object[] params = new Object[] { id };    
    List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));    
    return (User) list.get(0);    

网上收集 
org.springframework.jdbc.core.PreparedStatementCreator 返回预编译SQL 不能于Object[]一起用

代码 
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {    
return con.prepareStatement(sql);    

1.增删改 
org.springframework.jdbc.core.JdbcTemplate 类(必须指定数据源dataSource)

代码 
template.update("insert into web_person values(?,?,?)",Object[]); 

代码 
template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ 匿名内部类 只能访问外部最终局部变量    
public void setValues(PreparedStatement ps) throws SQLException {    
ps.setInt(index++,3);    
}); 

org.springframework.jdbc.core.PreparedStatementSetter 接口 处理预编译SQL

代码 
public void setValues(PreparedStatement ps) throws SQLException {    
ps.setInt(index++,3);    

2.查询JdbcTemplate.query(String,[Object[]/PreparedStatementSetter],RowMapper/RowCallbackHandler) 
org.springframework.jdbc.core.RowMapper 记录映射接口 处理结果集

代码 
public Object mapRow(ResultSet rs, int arg1) throws SQLException {   int表当前行数    
person.setId(rs.getInt("id"));    
}    
List template.query("select * from web_person where id=?",Object[],RowMapper); 

org.springframework.jdbc.core.RowCallbackHandler 记录回调管理器接口 处理结果集

代码 
template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){    
public void processRow(ResultSet rs) throws SQLException {    
person.setId(rs.getInt("id"));    
}); 

 

 

      Spring-JdbcTemplate 总结

1. 查询单个对象:

a)      基本类型

================================================

下面两个方法主要适用于静态sql

◆     public Object queryForObject(String sql, RowMapper rowMapper)

◆     public Object queryForObject(String sql, Class requiredType)

注意:requiredType 只能是基本类型的class,只针对基本类型有效

◆     public Object queryForObject(String sql, Object[] args, Class requiredType)

◆     public Object queryForObject(String sql, Object[] args, RowMapper rowMapper)

◆     public Object queryForObject(String sql, Object[] args, int[] argTypes, Class requiredType)

注:其中argTypes 可以使用java.sql.Types常量类中的常量值

◆     public Object queryForObject(String sql, Object[] args, int[] argTypes, RowMapper rowMapper)

注: rowMapper是一个回调接口

以下主要用于查询数值对象

◆     public int queryForInt(String sql, Object[] args)

◆     public long queryForLong(String sql, Object[] args)

==================================================

下面的方法将返回的各个列封装成map对象,key为列名,value为列值.只能一行数据,不能返回多行数据.

◆     public Map queryForMap(String sql, Object[] args)

b)      引用类型

◆     public Object queryForObject(String sql, RowMapper rowMapper)

◆     public Object queryForObject(String sql, Object[] args, RowMapper rowMapper)

◆     public Map queryForMap(String sql, Object[] args)

2. 查询多个对象

a)      基本类型:

◆     public List queryForList(String sql, Object[] args)

注:返回的list的每个元素都是一个map对象,该map对象封装了一行数据且只有一行数据,包括要查询的列字段

b)      引用类型:   

◆     public List queryForList(String sql, Object[] args)

        Iterator iter =  this.jdbcTemplate.queryForList(sql,new Object[]{}).iterator();

        List list = new ArrayList();

        while(iter.hasNext()){

            User user = new User();

            Map map = (Map) iter.next();

            Set<Entry<String, String>> set = map.entrySet();

            Iterator<Entry<String, String>> iter2 = set.iterator();

            Entry<String, String> entry = iter2.next();

            user.setUsername(entry.getValue());

            entry = iter2.next();

            user.setPassword(entry.getValue());

            list.add(user);

       }

◆     public List query(String sql, Object[] args, RowMapper rowMapper)

注:返回的list 中的元素可以是引用类型的对象.

◆       public Object execute(ConnectionCallback action)

注:使用回调接口.将各个字段值封装成引用类型的对象,然后以list方式返回.

3.  修改操作.适用于增、删、改

◆     public int update(String sql, Object[] args)

4.  批处理

 String sql = "insert into user(username,password) values(?,?)";

       final List list = new ArrayList();

       for(int i = 0;i < 5 ; i++){

           User user = new User();

           user.setPassword("dog" + i);

           user.setUsername("dog" + i);

           list.add(user);

       }

       int [] rst = this.jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter(){

           public int getBatchSize() {

              return list.size();

           }

           public void setValues(PreparedStatement ps, int i)

                  throws SQLException {

              User user = (User) list.get(i);

              ps.setString(1, user.getUsername());

              ps.setString(2, user.getPassword());

           }

      });

 

 

*************************************************************************************************************************************************

  1. 实现一、在内部建立内联类实现<SPANclass=hilite1>RowMapper</SPAN>接口   
  2. packagehysteria.contact.dao.impl;   
  3.   
  4. importjava.sql.ResultSet;   
  5. importjava.sql.SQLException;   
  6. importjava.sql.Types;   
  7. importjava.util.List;   
  8.   
  9. importorg.springframework.jdbc.core.JdbcTemplate;   
  10. importorg.springframework.jdbc.core.<SPANclass=hilite1>RowMapper</SPAN>;   
  11.   
  12. importhysteria.contact.dao.ItemDAO;   
  13. importhysteria.contact.domain.Item;   
  14.   
  15. publicclassItemDAOImplimplementsItemDAO {   
  16. privateJdbcTemplate jdbcTemplate;   
  17.   
  18. publicvoidsetJdbcTemplate(JdbcTemplate jdbcTemplate) {   
  19.   this.jdbcTemplate = jdbcTemplate;   
  20. }   
  21.   
  22. publicItem insert(Item item) {   
  23.    String sql ="INSERT INTO items(user_id,name,phone,email) VALUES(?,?,?,?)";   
  24.    Object[] params =newObject[]{item.getUserId(),item.getName(),item.getPhone(),item.getEmail()};   
  25.   int[] types =newint[]{Types.INTEGER,Types.VARCHAR,Types.CHAR,Types.VARCHAR};   
  26.    jdbcTemplate.update(sql,params,types);   
  27.   returnitem;   
  28. }   
  29.   
  30. publicItem update(Item item) {   
  31.    String sql ="UPDATE items SET name = ?, phone = ?, email = ? WHERE id = ?";   
  32.    Object[] params =newObject[] {item.getName(),item.getPhone(),item.getEmail(),item.getId()};   
  33.   int[] types =newint[] {Types.VARCHAR,Types.CHAR,Types.VARCHAR,Types.VARCHAR,Types.INTEGER};   
  34.    jdbcTemplate.update(sql,params,types);   
  35.   
  36.   returnitem;   
  37. }   
  38.   
  39. publicvoiddelete(Item item) {   
  40.    String sql ="DELETE FROM items WHERE id = ?";   
  41.    Object[] params =newObject[] {item.getId()};   
  42.   int[] types =newint[]{Types.INTEGER};   
  43.    jdbcTemplate.update(sql,params,types);   
  44. }   
  45.   
  46. publicItem findById(intid) {   
  47.    String sql ="SELECT * FROM items WHERE id = ?";   
  48.    Object[] params =newObject[] {id};   
  49.   int[] types =newint[] {Types.INTEGER};   
  50.    List items = jdbcTemplate.query(sql,params,types,newItemMapper());   
  51.   if(items.isEmpty()){   
  52.    returnnull;   
  53.    }   
  54.   return(Item)items.get(0);   
  55. }   
  56.   
  57. publicList<Item> findAll() {   
  58.    String sql ="SELECT * FROM items";   
  59.   returnjdbcTemplate.query(sql,newItemMapper());   
  60. }   
  61.   
  62.   
  63. publicList<Item> findAllByUser(intuser_id) {   
  64.    String sql ="SELECT * FROM items WHERE user_id = ?";   
  65.    Object[] params =newObject[]{user_id};   
  66.   int[] types =newint[]{Types.INTEGER};   
  67.    List items = jdbcTemplate.query(sql,params,types,newItemMapper());   
  68.   returnitems;   
  69. }   
  70.   
  71. protectedclassItemMapperimplements<SPANclass=hilite1>RowMapper</SPAN> {   
  72.   
  73.   publicObject mapRow(ResultSet rs,introwNum)throwsSQLException {   
  74.     Item item =newItem();   
  75.     item.setId(rs.getInt("id"));   
  76.     item.setUserId(rs.getInt("user_id"));   
  77.     item.setName(rs.getString("name"));   
  78.     item.setPhone(rs.getString("phone"));   
  79.     item.setEmail(rs.getString("email"));   
  80.   
  81.    returnitem;   
  82.    }   
  83.   
  84. }   
  85.   
  86.   
  87. }  

 <转:http://hanhongke123.blog.163.com/blog/static/6222349420122135204201/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值