(殘夢追月原創(chuàng),轉(zhuǎn)載請注明)
本文地址:http://m.tkk7.com/cmzy/archive/2008/09/11/228271.html?
?? 今天看SpringAPI的時候無意中發(fā)現(xiàn)了Spring2.5新增了一個RowMapper的實現(xiàn)類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和實體類的字段進行實現(xiàn)自動映射。
?? 一個具體的例子如下:
?? 假如有這樣一個表,SQL-Server2000的建表腳本如下:
?? 為此,我們編寫一個對應的實體類admin,它是一個標準的javaBean,代碼如下:
?? 以前,在相應的AdminDAO中,我們以前是這么做滴,看起來很麻煩,如果一個表的字段很多的話,就要人命了,我們必須不停的set、get:
?? 可見,我們必須的手工對ResultSet和Admin進行映射。而現(xiàn)在,我們只是需要這樣:
??? 呵呵,只是一句話就完全搞定了……Sprin會為我們自動映射……顯然這樣比以前方便多了。我們還可以把它用在其它任何使用RowMapper的場合……畢竟它繼承自RowMapper……
??? 需要注意的是:BeanPropertyRowMapper是根據(jù)字段名和實體類中的標準Setter方法進行映射滴。也就是說,我們需要使表中的字段名和實體類的成員變量名稱一致。
By:殘夢追月
posted on 2008-09-11 09:33
殘夢追月 閱讀(6184)
評論(8) 編輯 收藏 所屬分類:
Spring