spring jdbc 自带的数据库列转对应的java Bean
先来创建一个表格
CREATE TABLE `dwz` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`<span style="color: red;">url_Short</span>` varchar(100) DEFAULT NULL,
`<span style="color: red;">createdcount</span>` int(11) DEFAULT '1',
`urlOriginal` varchar(200) DEFAULT NULL,
`<span style="color: red;">success</span>` tinyint(2) DEFAULT '0',
`CREATEDTIME` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updatedTime` datetime DEFAULT NULL,
`deleted` tinyint(2) DEFAULT '0',
`version` int(11) DEFAULT '1',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
为这张表创建一个 Dwz.java Bean
package com.denghb.dwz.domain;
import java.io.Serializable;
import java.util.Date;
public class Dwz implements Serializable {
private static final long serialVersionUID = 652817747802181261L;
private Integer id;
private String urlShort;
private String urlOriginal;
private Integer createdCount;
private Boolean success;
private Date createdTime;
private Date updatedTime;
private Boolean deleted;
private Integer version;
...get&set
}
主角登场
// 代码片段
String sql = "select * from dwz where deleted = ?";
// Dwz dwz = jdbcTemplate.queryForObject(sql , BeanPropertyRowMapper.newInstance(Dwz.class), true);
List<Dwz> list = jdbcTemplate.query(sql , BeanPropertyRowMapper.newInstance(Dwz.class), true);
// 在spring容器中执行后输出日志
...JdbcTemplate]Executing prepared SQL statement [select * from dwz where deleted = ?]
...BeanPropertyRowMapper]Mapping column 'id' to property 'id' of type [java.lang.Integer]
...BeanPropertyRowMapper]Mapping column 'url_Short' to property 'urlShort' of type [java.lang.String]
...BeanPropertyRowMapper]Mapping column 'createdcount' to property 'createdCount' of type [java.lang.Integer]
...BeanPropertyRowMapper]Mapping column 'urlOriginal' to property 'urlOriginal' of type [java.lang.String]
...BeanPropertyRowMapper]Mapping column 'success' to property 'success' of type [java.lang.Boolean]
...BeanPropertyRowMapper]Mapping column 'CREATEDTIME' to property 'createdTime' of type [java.util.Date]
...BeanPropertyRowMapper]Mapping column 'updatedTime' to property 'updatedTime' of type [java.util.Date]
...BeanPropertyRowMapper]Mapping column 'deleted' to property 'deleted' of type [java.lang.Boolean]
...BeanPropertyRowMapper]Mapping column 'version' to property 'version' of type [java.lang.Integer]
这样就将表dwz转成了Dwz这个java对象
这个是我之前的奇葩实现
原来的:ResultSet >> List<Map<String,Object>> >> JSONObject >> Java Bean
现在的:ResultSet >> Java Bean
唉,还是得多看Spring API
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名,转载请标明出处;