ibatis基础(二):查询所有的对象

假设数据库的student表中有如下的字段和数据:

对应的Student.java如下:

 1 public class Student {
2 private Integer id;
3 private String name;
4 private float score;
5 public Integer getId() {
6 return id;
7 }
8 public void setId(Integer id) {
9 this.id = id;
10 }
11 public String getName() {
12 return name;
13 }
14 public void setName(String name) {
15 this.name = name;
16 }
17 public float getScore() {
18 return score;
19 }
20 public void setScore(float score) {
21 this.score = score;
22 }
23 @Override
24 public String toString() {
25 return this.id+"\t"+this.name+"\t"+this.score;
26 }
27 }

此时我们要查询所有的对象需在Student.xml中添加如下代码:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-2.dtd"
>

<sqlMap>
<!--typeAlias用于简写 -->
<typeAlias alias="Student" type="com.jim.bean.Student"/>
<!-- id代表索引名称 resultClass代表返回类型-->
<select id="SelectAllStudent" resultClass="Student">
select *
from student
</select>
</sqlMap>

编写junit进行测试:

 1     @Test
2 public void queryAllStudent() throws Exception{
3 Reader reader=Resources.getResourceAsReader("SqlMapConfig.xml");//读取总配置文件
4 SqlMapClient sqlmapclient=SqlMapClientBuilder.buildSqlMapClient(reader);//创建SqlMapClient来操作数据库
5 reader.close();
6 List<Student> students=sqlmapclient.queryForList("SelectAllStudent");//调用我们写在xml中的sql语句
7 for(Student student:students){
8 System.out.println(student);
9 }
10 }

查看结果,成功查询出所以学生的信息:




posted @ 2011-12-04 15:11  一直在等  阅读(835)  评论(0编辑  收藏  举报