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 常規用法總結:
- jdbcTemplate.execute( "CREATETABLEUSER(user_idinteger,namevarchar(100))" );
2、如果是UPDATE或INSERT,可以用update()方法。
- jdbcTemplate.update( "INSERTINTOUSERVALUES('"
- +user.getId()+ "','"
- +user.getName()+ "','"
- +user.getSex()+ "','"
- +user.getAge()+ "')" );
3、帶參數的更新
- jdbcTemplate.update( "UPDATEUSERSETname=?WHEREuser_id=?" , new Object[]{name,id});
- jdbcTemplate.update( "INSERTINTOUSERVALUES(?,?,?,?)" , new Object[]{user.getId(),user.getName(),user.getSex(),user.getAge()});
4、使用JdbcTemplate進行查詢時,使用queryForXXX()等方法
- int count=jdbcTemplate.queryForInt( "SELECTCOUNT(*)FROMUSER" );
- Stringname=(String)jdbcTemplate.queryForObject( "SELECTnameFROMUSERWHEREuser_id=?" , new Object[]{id},java.lang.String. class );
- Listrows=jdbcTemplate.queryForList( "SELECT*FROMUSER" );
- Listrows=jdbcTemplate.queryForList( "SELECT*FROMUSER" );
- Iteratorit=rows.iterator();
- while (it.hasNext()){
- MapuserMap=(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 Stringid=user.getId();
- final Stringname=user.getName();
- final Stringsex=user.getSex()+ "" ;
- final int age=user.getAge();
- jdbcTemplate.update( "INSERTINTOUSERVALUES(?,?,?,?)" ,
- new PreparedStatementSetter(){
- public void setValues(PreparedStatementps) throws SQLException{
- ps.setString( 1 ,id);
- ps.setString( 2 ,name);
- ps.setString( 3 ,sex);
- ps.setInt( 4 ,age);
- }
- });
- final Useruser= new User();
- jdbcTemplate.query( "SELECT*FROMUSERWHEREuser_id=?" ,
- new Object[]{id},
- new RowCallbackHandler(){
- public void processRow(ResultSetrs) 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 ObjectmapRow(ResultSetrs, int index) throws SQLException{
- Useruser= 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 ListfindAllByRowMapperResultReader(){
- Stringsql= "SELECT*FROMUSER" ;
- return jdbcTemplate.query(sql, new RowMapperResultReader( new UserRowMapper()));
- }
在getUser(id)里面使用UserRowMapper
- public UsergetUser( final Stringid) throws DataAccessException{
- Stringsql= "SELECT*FROMUSERWHEREuser_id=?" ;
- final Object[]params= new Object[]{id};
- Listlist=jdbcTemplate.query(sql,params, new RowMapperResultReader( new UserRowMapper()));
- return (User)list.get( 0 );
- }
網上收集
org.springframework.jdbc.core.PreparedStatementCreator 返回預編譯SQL 不能于Object[]一起用
- public PreparedStatementcreatePreparedStatement(Connectioncon) throws SQLException{
- return con.prepareStatement(sql);
- }
1.增刪改
org.springframework.jdbc.core.JdbcTemplate 類(必須指定數據源dataSource)
- template.update( "insertintoweb_personvalues(?,?,?)" ,Object[]);
或
- template.update( "insertintoweb_personvalues(?,?,?)" , new PreparedStatementSetter(){匿名內部類只能訪問外部最終局部變量
- public void setValues(PreparedStatementps) throws SQLException{
- ps.setInt(index++, 3 );
- });
org.springframework.jdbc.core.PreparedStatementSetter 接口 處理預編譯SQL
- public void setValues(PreparedStatementps) throws SQLException{
- ps.setInt(index++, 3 );
- }
2.查詢JdbcTemplate.query(String,[Object[]/PreparedStatementSetter],RowMapper/RowCallbackHandler)
org.springframework.jdbc.core.RowMapper 記錄映射接口 處理結果集
- public ObjectmapRow(ResultSetrs, int arg1) throws SQLException{ int 表當前行數
- person.setId(rs.getInt( "id" ));
- }
- Listtemplate.query( "select*fromweb_personwhereid=?" ,Object[],RowMapper);
org.springframework.jdbc.core.RowCallbackHandler 記錄回調管理器接口 處理結果集
- template.query( "select*fromweb_personwhereid=?" ,Object[], new RowCallbackHandler(){
- public void processRow(ResultSetrs) throws SQLException{
- person.setId(rs.getInt( "id" ));
- });
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
