发现了Spring2.5里的一个新东西, BeanPropertyRowMapper类。
(残梦追月原创,转载请注明)
本文地址:http://www.blogjava.net/cmzy/archive/2008/09/11/228271.html?
?? 今天看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的建表脚本如下:
?? 可见,我们必须的手工对ResultSet和Admin进行映射。而现在,我们只是需要这样:
??? 呵呵,只是一句话就完全搞定了……Sprin会为我们自动映射……显然这样比以前方便多了。我们还可以把它用在其它任何使用RowMapper的场合……毕竟它继承自RowMapper……
??? 需要注意的是:BeanPropertyRowMapper是根据字段名和实体类中的标准Setter方法进行映射滴。也就是说,我们需要使表中的字段名和实体类的成员变量名称一致。
?
15 楼 javeye 2008-09-16 原来在spring2.0里也有一个:org.springframework.jdbc.core.RowMapper只是需要我们自己去实现这个接口的mapRow方法来实现转换,现在这个类的确让这个处理变得容易了许多。呵呵 16 楼 cmzy 2008-09-16 引用原来在spring2.0里也有一个:org.springframework.jdbc.core.RowMapper只是需要我们自己去实现这个接口的mapRow方法来实现转换,现在这个类的确让这个处理变得容易了许多。呵呵这个就是哪个接口的一个实现类啊……呵呵 17 楼 ironsabre 2010-05-17 raymond2006k 写道不错的东东。
不过,myyate 网友说的字段名和属性名不一致的情况很多时候是存在的,例如:
字段名是:user_name, 属性名是 userName;
这就是Hibernate等ORM框架中存在 hbm.xml 映射文件的原因。
或者 BeanPropertyRowMapper 可以实现一个子类,针对上面的例子按指定规则进行映射。
实际项目中,大部分都可以按 camel name 规则进行映射。
user_name可以自动映射到userName的。
18 楼 ironsabre 2010-05-22 cmzy 写道引用
upheart 20 分钟前 删除
不知能不能配置映射规则?比如数据库字段user_name映射成bean的userName,可以向rails学习一下。
这个你可以继承这个类,自己定义映射规则嘛。
大哥,你到底有没有用过啊。这个本来就是默认支持的。