背景:
最近公司需要做一个小工具,就是通过执行我们自己写的sql,然后将执行sql的数据进行下载。
因为在公司一直用的ibatis,一直用sqlclient执行sql。发现这个需求不能做一把映射。查看资料发现用spring的jdbctemplate是可以做的。
需求:
需要做这个功能必须在执行sql以后获取到它的获取的字段。与每个字段对应的关系。
实现:
1、使用spring jdbcTemplate,首先通过声明jdbcTemplate Bean(dateSource已经声明)
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
<property name="dataSource" ref="dataSource" />
</bean>
引入jdbc的包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
2、使用jdbc执行sql并获取返回字段与每个字段对应的属性值:
public List<Map<String, Object>> queryForList(String sql) throws DataAccessException {
return query(sql, getColumnMapRowMapper());
}
查看这个方法的注释:
Execute a query for a result list, given static SQL.
Uses a JDBC Statement, not a PreparedStatement. If you want to execute
a static query with a PreparedStatement, use the overloaded
queryForList method with null as argument array.The results will be mapped to a List (one entry for each row) of Maps
(one entry for each column using the column name as the key). Each
element in the list will be of the form returned by this interface’s
queryForMap() methods.
表示这个方法会执行一个sql,并返回一个map的list,map里面数据key为我们查询出来的字段,value为我们查询出字段的对应值。
所以我们执行sql为:
//通过执行sql获取返回属性与对应属性值
List<Map<String, Object>> list = exportService.export(sql);
3、明确我们应该使用哪个方法,我们要展示数据
首先我们获取所有的属性字段:
Map<String, Object> map = list.get(0);
if (map == null) {
return;
}
List<String> headers = new ArrayList<String>();
List<Class<?>> types = new ArrayList<Class<?>>();
for (String key : map.keySet()) {
headers.add(key);
types.add(Object.class);
}
其中headers表示我们要展示的头既我们的属性:
然后组装出每个属性对应的属性值:
//根据数据填充下面真实数据
for (int i = 0; i < list.size(); i++) {
Object object = list.get(i);//这个object其实就是map<String,Object>
if (object == null) {
continue;
}
row = sheet.createRow(i + 1);// 有个头,所以都需要加1
for (int j = 0; j < headers.size(); j++) {
try {
String value = null;
Class<?> type = types.get(j);
//如果是Object是时间格式,就把格式转换为时间
if(type!=null && type.equals(Date.class)){
try {
Date date = (Date) PropertyUtils.getProperty(object, propertys.get(j));
value = sdf.format(date);
} catch (Exception e) {
// TODO: handle exception
}
}else {
//使用java从object中获取数据,propertys.get(j)既获取到要取的属性值
value = BeanUtils.getProperty(object, propertys.get(j));
}
row.createCell(j).setCellValue(value);
} catch (IllegalAccessException e) {
logger.error("异常:" + e.getMessage(), e);
} catch (InvocationTargetException e) {
logger.error("异常:" + e.getMessage(), e);
} catch (NoSuchMethodException e) {
logger.error("异常:" + e.getMessage(), e);
}
}
}
上面就是Spring获取到 执行返回未知数据的sql,并获取属性值的数据。