使用SpringJDBC封装数据为对象

spring 对数据库返回的dataset 数据有几种封装的方法直接返回想要的对象类型

需要自己进行封装参数

一下只列举两种方法可实现对象的封装


import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

/**
 *
 * @author julong
 * @date 2015-8-18 下午03:20:02
 */
public class OrderFormRecodDaoImpl extends JdbcDaoSupport implements OrderFormRecodDao {
	private static Logger logger = Logger.getLogger(OrderFormRecodDaoImpl.class);
	public OrderFormRecodInfo getOrderFormRecodInfo(OrderFormRecodInfo OrderFormRecodInfo) {
		// TODO Auto-generated method stub
		String sql = "SELECT * FROM wx_order_form_record WHERE A = '20150402195602169' ";
		logger.info("sql:"+sql);
		//第一种方式
		List orderFormRecodInfoList = this.getJdbcTemplate().query(sql, new Object[]{}, new OrderFormRecodInfoMapper());
		//第二种方式
		//List orderFormRecodInfoList = this.getJdbcTemplate().query(sql, new Object[]{}, rowMapper);
		if(0 != orderFormRecodInfoList.size()){
			orderFormRecodInfo = orderFormRecodInfoList.get(0);
		}
		return OrderFormRecodInfo;
	}
	/**
	 * 封装对象
	 *
	 * @author julong
	 * @date 2015-8-18 下午07:59:10
	 */
	private static class OrderFormRecodInfoMapper implements ParameterizedRowMapper{

		public OrderFormRecodInfo mapRow(ResultSet resultSet, int arg1)
				throws SQLException {
			// TODO Auto-generated method stub
			OrderFormRecodInfo orderFormRecodInfo = new WxOrderFormRecodInfo();
			orderFormRecodInfo.setF_order_num(resultSet.getString("f_order_num"));
			orderFormRecodInfo.setF_open_id(resultSet.getString("f_open_id"));
			orderFormRecodInfo.setF_time(resultSet.getString("f_time"));
			return orderFormRecodInfo;
		}

	}
	/**
	 * 封装对象
	 */
	private static RowMapper rowMapper = new RowMapper() {

		public Object mapRow(ResultSet resultSet, int arg1) throws SQLException {
			// TODO Auto-generated method stub
			OrderFormRecodInfo orderFormRecodInfo = new OrderFormRecodInfo();
			OrderFormRecodInfo.setF_order_num(resultSet.getString("f_order_num"));//订单编号
			OrderFormRecodInfo.setF_open_id(resultSet.getString("f_open_id"));//下单人
			OrderFormRecodInfo.setF_time(resultSet.getString("f_time"));//下单时间
			return orderFormRecodInfo;
		}
	};
}

 

你可能感兴趣的:(Spring)