码迷,mamicode.com
首页 > 移动开发 > 详细

Spring使用RowMapper将数据中的每一行封装成用户定义的类

时间:2016-10-13 19:21:41      阅读:2563      评论:0      收藏:0      [点我收藏+]

标签:

1.dao

public interface MapperSelecteAllEmpDao {
    public List<Emp> all();
}

2.实现类

public class MapperAllEmpImpl extends JdbcDaoSupport implements
        MapperSelecteAllEmpDao {

    @Override
    public List<Emp> all() {
        String sql = "select * from emp";
        List<Emp> list = this.getJdbcTemplate().query(sql, new EmpRowMapper());
        return list;
    }
}

3.继承rowMapper接口,返回自定义类型

public class EmpRowMapper implements RowMapper<Emp> {

    @Override
    public Emp mapRow(ResultSet rs, int arg1) throws SQLException {
        Emp emp = new Emp();
        emp.setId(rs.getInt("id"));
        emp.setName(rs.getString("name"));
        emp.setAge(rs.getInt("age"));
        return emp;
    }
}

4.测试

@Test
    // Spring使用rowMapper查询表中所有记录
    public void rowMapperAll() {
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");

        MapperSelecteAllEmpDao mapperSelectAll = (MapperSelecteAllEmpDao) ac
                .getBean("mapperAll");

        List<Emp> empList = mapperSelectAll.all();

        for (Emp emp : empList) {
            System.out.println(emp.getName());
        }
    }

 

Spring使用RowMapper将数据中的每一行封装成用户定义的类

标签:

原文地址:http://www.cnblogs.com/cnsdhzzl/p/5957327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!