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());
}
}