spring JdbcTemplate 的若干问题

来源:互联网 发布:爱青岛网络公开课 编辑:程序博客网 时间:2024/04/30 03:23

spring的javadoc上讲getObject(String, Object[], Class) will return NULL if the result of the query is NUL
这里有0行和nullresult的区别
0行: select salary from user where 1 = 2
null result: select max(salary) from user where 1 = 2 返回就是null
0行一定抛出IncorrectResultSizeDataAccessException异常
原因如下
ResultSetMetaData rsmd = rs.getMetaData();
int nrOfColumns = rsmd.getColumnCount();这里返回ResultSet的列数
  if (nrOfColumns != 1) {
   throw new IncorrectResultSizeDataAccessException(
     "Expected single column but found " + nrOfColumns, 1, nrOfColumns);
  }
0行,多于1行,就抛异常了
 最好还是用QueryForList,返回的list的size为0,就是0行
 
还有oracle 10g的问题,jdbc驱动版本10.1.0.20
getObject返回一个日期类型为java.util.Date
但是这个日期只有年-月-日,没有时-分-秒,因为10g对于DATE类型的列,
getObject().getClass().getName()得到 java.sql.Date
System.out.println(rs.getObject("date_created") + " " + rs.getObject("date_created").getClass());
得到 2005-10-06 class java.sql.Date
要得到全部日期,必须使用oracle.sql.TIMESTAMP
但是使用queryForObject("sql", Timestamp.class)
得到org.springframework.dao.TypeMismatchDataAccessException异常
java.sql.Timestamp] and could not be converted to required type [java.sql.Timestamp] 很是莫名其妙
只好使用java -Doracle.jdbc.V8Compatibility="true" MyApp解决

 

 

 

以下是对JdbcTemplate 常规用法总结:

 

Java代码 复制代码
  1. jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");  
[java] view plaincopyprint?
  1. jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");  


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

Java代码 复制代码
  1. jdbcTemplate.update("INSERT INTO USER VALUES('"  
  2.            + user.getId() + "', '"  
  3.            + user.getName() + "', '"  
  4.            + user.getSex() + "', '"  
  5.            + user.getAge() + "')");  
[java] view plaincopyprint?
  1. jdbcTemplate.update("INSERT INTO USER VALUES('"  
  2.            + user.getId() + "', '"  
  3.            + user.getName() + "', '"  
  4.            + user.getSex() + "', '"  
  5.            + user.getAge() + "')");  


3、带参数的更新

Java代码 复制代码
  1. jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?"new Object[] {name, id});  
[java] view plaincopyprint?
  1. jdbcTemplate.update("UPDATE USER SET name = ? WHERE user_id = ?"new Object[] {name, id});  

 

Java代码 复制代码
  1. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)"new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()});  
[java] view plaincopyprint?
  1. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)"new Object[] {user.getId(), user.getName(), user.getSex(), user.getAge()});  


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

Java代码 复制代码
  1. int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");  
[java] view plaincopyprint?
  1. int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM USER");  


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


Java代码 复制代码
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");  
[java] view plaincopyprint?
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");  


Java代码 复制代码
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");   
  2. Iterator it = rows.iterator();   
  3. while(it.hasNext()) {   
  4.     Map userMap = (Map) it.next();   
  5.     System.out.print(userMap.get("user_id") + "/t");   
  6.     System.out.print(userMap.get("name") + "/t");   
  7.     System.out.print(userMap.get("sex") + "/t");   
  8.     System.out.println(userMap.get("age") + "/t");   
  9. }  
[java] view plaincopyprint?
  1. List rows = jdbcTemplate.queryForList("SELECT * FROM USER");  
  2. Iterator it = rows.iterator();  
  3. while(it.hasNext()) {  
  4.     Map userMap = (Map) it.next();  
  5.     System.out.print(userMap.get("user_id") + "/t");  
  6.     System.out.print(userMap.get("name") + "/t");  
  7.     System.out.print(userMap.get("sex") + "/t");  
  8.     System.out.println(userMap.get("age") + "/t");  
  9. }  



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

JDBC的PreparedStatement

Java代码 复制代码
  1. final String id = user.getId();   
  2. final String name = user.getName();   
  3. final String sex = user.getSex() + "";   
  4. final int age = user.getAge();   
  5.   
  6. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",   
  7.                      new PreparedStatementSetter() {   
  8.                          public void setValues(PreparedStatement ps) throws SQLException {   
  9.                              ps.setString(1, id);   
  10.                              ps.setString(2, name);             
  11.                              ps.setString(3, sex);   
  12.                              ps.setInt(4, age);   
  13.                          }   
  14.                      });  
[java] view plaincopyprint?
  1. final String id = user.getId();  
  2. final String name = user.getName();  
  3. final String sex = user.getSex() + "";  
  4. final int age = user.getAge();  
  5.   
  6. jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",  
  7.                      new PreparedStatementSetter() {  
  8.                          public void setValues(PreparedStatement ps) throws SQLException {  
  9.                              ps.setString(1, id);  
  10.                              ps.setString(2, name);            
  11.                              ps.setString(3, sex);  
  12.                              ps.setInt(4, age);  
  13.                          }  
  14.                      });  


Java代码 复制代码
  1. final User user = new User();   
  2. jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",   
  3.                     new Object[] {id},   
  4.                     new RowCallbackHandler() {   
  5.                         public void processRow(ResultSet rs) throws SQLException {   
  6.                             user.setId(rs.getString("user_id"));   
  7.                             user.setName(rs.getString("name"));   
  8.                             user.setSex(rs.getString("sex").charAt(0));   
  9.                             user.setAge(rs.getInt("age"));   
  10.                         }   
  11.                     });  
[java] view plaincopyprint?
  1. final User user = new User();  
  2. jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",  
  3.                     new Object[] {id},  
  4.                     new RowCallbackHandler() {  
  5.                         public void processRow(ResultSet rs) throws SQLException {  
  6.                             user.setId(rs.getString("user_id"));  
  7.                             user.setName(rs.getString("name"));  
  8.                             user.setSex(rs.getString("sex").charAt(0));  
  9.                             user.setAge(rs.getInt("age"));  
  10.                         }  
  11.                     });  




Java代码 复制代码
  1. class UserRowMapper implements RowMapper {   
  2.     public Object mapRow(ResultSet rs, int index) throws SQLException {   
  3.         User user = new User();   
  4.   
  5.         user.setId(rs.getString("user_id"));   
  6.         user.setName(rs.getString("name"));   
  7.         user.setSex(rs.getString("sex").charAt(0));   
  8.         user.setAge(rs.getInt("age"));   
  9.   
  10.         return user;   
  11.     }   
  12. }   
  13.   
  14. public List findAllByRowMapperResultReader() {   
  15.     String sql = "SELECT * FROM USER";   
  16.     return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));   
  17. }  
[java] view plaincopyprint?
  1. class UserRowMapper implements RowMapper {  
  2.     public Object mapRow(ResultSet rs, int index) throws SQLException {  
  3.         User user = new User();  
  4.   
  5.         user.setId(rs.getString("user_id"));  
  6.         user.setName(rs.getString("name"));  
  7.         user.setSex(rs.getString("sex").charAt(0));  
  8.         user.setAge(rs.getInt("age"));  
  9.   
  10.         return user;  
  11.     }  
  12. }  
  13.   
  14. public List findAllByRowMapperResultReader() {  
  15.     String sql = "SELECT * FROM USER";  
  16.     return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));  
  17. }  



在getUser(id)里面使用UserRowMapper

Java代码 复制代码
  1. public User getUser(final String id) throws DataAccessException {   
  2.     String sql = "SELECT * FROM USER WHERE user_id=?";   
  3.     final Object[] params = new Object[] { id };   
  4.     List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));   
  5.   
  6.     return (User) list.get(0);   
  7. }  
[java] view plaincopyprint?
  1. public User getUser(final String id) throws DataAccessException {  
  2.     String sql = "SELECT * FROM USER WHERE user_id=?";  
  3.     final Object[] params = new Object[] { id };  
  4.     List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper()));  
  5.   
  6.     return (User) list.get(0);  
  7. }  



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

Java代码 复制代码
  1. public PreparedStatement createPreparedStatement(Connection con) throws SQLException {   
  2.  return con.prepareStatement(sql);   
  3. }  
[java] view plaincopyprint?
  1. public PreparedStatement createPreparedStatement(Connection con) throws SQLException {  
  2.  return con.prepareStatement(sql);  
  3. }  


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

Java代码 复制代码
  1. template.update("insert into web_person values(?,?,?)",Object[]);  
[java] view plaincopyprint?
  1. template.update("insert into web_person values(?,?,?)",Object[]);  


  或

Java代码 复制代码
  1. template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ 匿名内部类 只能访问外部最终局部变量   
  2.   
  3.  public void setValues(PreparedStatement ps) throws SQLException {   
  4.   ps.setInt(index++,3);   
  5. });  
[java] view plaincopyprint?
  1. template.update("insert into web_person values(?,?,?)",new PreparedStatementSetter(){ 匿名内部类 只能访问外部最终局部变量  
  2.   
  3.  public void setValues(PreparedStatement ps) throws SQLException {  
  4.   ps.setInt(index++,3);  
  5. });  


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

Java代码 复制代码
  1. public void setValues(PreparedStatement ps) throws SQLException {   
  2.  ps.setInt(index++,3);   
  3. }  
[java] view plaincopyprint?
  1. public void setValues(PreparedStatement ps) throws SQLException {  
  2.  ps.setInt(index++,3);  
  3. }  


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

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


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

Java代码 复制代码
  1. template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){   
  2.  public void processRow(ResultSet rs) throws SQLException {   
  3.   person.setId(rs.getInt("id"));   
  4. });  
[java] view plaincopyprint?
  1. template.query("select * from web_person where id=?",Object[],new RowCallbackHandler(){  
  2.  public void processRow(ResultSet rs) throws SQLException {  
  3.   person.setId(rs.getInt("id"));  
  4. });  
原创粉丝点击