天天看点

JdbcTemplate 版本4以上的queryforObject和queryforList的实现

       书本和旧一点的网路资料都有提供queryforobject和queryforlist的方法,貌似都支持ORM的直接转换。但自己用maven配置的jdbctemplate 4.1.9,则不行,一直报IncorrectResultSetColumnCountException: Incorrect column count: expected 1,     actual...的错误,后来查资料发现4以后不支持了,要用指定RowMapper,幸好有BeanPropertyRowMapper的支持,不用手打一堆setxxx垃圾代码。

     下面代码实现了从表中获得单一bean和bean list,被注释掉的版本4已经不支持了:

package com.freestyle.test.dao;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import com.freestyle.jpatest.model.TaUser;
import com.freestyle.spring.BaseNamedParamJdbcDaoSupport;

public class UserDAO extends BaseNamedParamJdbcDaoSupport{
	private static final String C_FETCH_SQL_SINGLE="select * from ta_user where fa_login=?";
	private static final String C_FETCH_SQL_LIST="select * from ta_user where fa_plant=?";
	public TaUser getSingleUser(String pvLoginName){
		//return mJdbcTemplate.queryForObject(C_FETCH_SQL_SINGLE, TaUser.class,new Object[]{pvLoginName});
		return mJdbcTemplate.queryForObject(C_FETCH_SQL_SINGLE, new BeanPropertyRowMapper<TaUser>(TaUser.class), new Object[]{pvLoginName});
	}
	public List<TaUser> getList(String pvPlant){
		return mJdbcTemplate.query(C_FETCH_SQL_LIST, new BeanPropertyRowMapper<TaUser>(TaUser.class), new Object[]{pvPlant});
		//return mJdbcTemplate.queryForList(C_FETCH_SQL_LIST, TaUser.class, new Object[]{pvPlant});
	}
}
           

以上是从表记录转换成Bean实体,但很多时候返回的数据供jstl使用,用map就可以了,代码:

public Map<String,Object> getSingleForMap(String pvLoginName){
		return mJdbcTemplate.queryForMap(C_FETCH_SQL_SINGLE, new Object[]{pvLoginName});
	}
public List<Map<String,Object>> getListForMap(String pvPlant){
		return mJdbcTemplate.queryForList(C_FETCH_SQL_LIST, new Object[]{pvPlant});
}
           

继续阅读