Spring框架JdbcTemplate類中查詢方法介紹

 今天看SpringAPI的時候無意中發現了Spring2.5新增了一個RowMapper的實現類org.springframework.jdbc.core.BeanPropertyRowMapper,但是貌似Spring的refrence裏面根本就沒提及到。Google了一下……貌似也莫得多少文檔。

    Spring API Doc的說明如下:

   RowMapper implementation that converts a row into a new instance of the specified mapped target class. The mapped target class must be a top-level class and it must have a default or no-arg constructor.

   Column values are mapped based on matching the column name as obtained from result set metadata to public setters for the corresponding properties. The names are matched either directly or by transforming a name separating the parts with underscores to the same name using "camel" case.

   Mapping is provided for fields in the target class for many common types, e.g.: String, boolean, Boolean, byte, Byte, short, Short, int, Integer, long, Long, float, Float, double, Double, BigDecimal, java.util.Date, etc.

   To facilitate mapping between columns and fields that don't have matching names, try using column aliases in the SQL statement like "select fname as first_name from customer".

   Please note that this class is designed to provide convenience rather than high performance. For best performance consider using a custom RowMapper.


   也就說,它可以把ResultSet和實體類的字段進行實現自動映射。

   一個具體的例子如下:

   假如有這樣一個表,SQL-Server2000的建表腳本如下:

/*
管理員表
*/
CREATE TABLE admin(
   id int identity(1,1) primary key,
   username varchar(20) not null,
   password varchar(32) not null,   
)

   爲此,我們編寫一個對應的實體類admin,它是一個標準的javaBean,代碼如下:

/**
 * 
 */
package db.demo;
/**
 * @author zhangyong
 * 
 * @version 8:11:57 PM
 * 
 */
public class Admin {
        private int id;
        private String username;
        private String password;


        public int getId() {
                return id;
        }


        public void setId(int id) {
                this.id = id;
        }


        public String getUsername() {
                return username;
        }


        public void setUsername(String username) {
                this.username = username;
        }


        public String getPassword() {
                return password;
        }


        public void setPassword(String password) {
                this.password = password;
        }
}


  在相應的AdminDAO中,如果用原生RowMapper做法如下注意的是rs.getString(USERNAME)  這裏數據庫字段要和實體屬性名保持一致,否則null

/**
 * 
 */
package db.demo;


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;


import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;


/**
 * @author zhangyong
 * 
 * @version 10:05:37 PM
 * 
 */
public class AdminDAO extends JdbcDaoSupport {


        private final String ID = "id";
        private final String USERNAME = "username";
        private final String PASSWORD = "password";
        private final String TABLE_NAME = "admin";


        /**
         * 查詢記錄總數<br/>
         */
        public List<Admin> queryAll() {
                final String sql = "Select * from " + TABLE_NAME;
                
                return getJdbcTemplate().query(sql, new RowMapper(){


                        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                                Admin admin = new Admin();
                                admin.setId(rs.getInt(ID));
                                admin.setUsername(rs.getString(USERNAME));
                                admin.setPassword(rs.getString(PASSWORD));
                                return admin;
                        }
                        
                });
        }
}


  現在使用BeanPropertyRowMapper 做法如下:注意的是使用BeanPropertyRowMapper實體屬性要和數據庫字段名有個規範:

自動綁定,需要列名稱和Java實體類名字一致,如:屬性名 “userName” 可以匹配數據庫中的列字段 "USERNAME" 或 “user_name”。這樣,我們就不需要一個個手動綁定了,大大提高了開發效率。java屬性形如:my_Num 對應數據庫字段MY_NUM 也是可以的。

/
 * 
 */
package db.demo;


import java.util.List;


import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;


/**
 * @author zhangyong
 * 
 * @version 10:05:37 PM
 * 
 */
public class AdminDAO extends JdbcDaoSupport {


        private final String TABLE_NAME = "admin";


        /**
         * 查詢記錄
         */
        public List<Admin> queryAll() {
                final String sql = "Select * from " + TABLE_NAME;
                
                return getJdbcTemplate().query(sql, new BeanPropertyRowMapper(Admin.class));
        }
}


查詢時使用RowMapper還是其他BeanPropertyRowMapper,ColumnMapRowMapper,SingleColumnRowMapper 定要注意數據庫和實體屬性命名。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章