<?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 namespace="teacher">
<typeAlias alias="Teacher" type="com.lsm.domain.Teacher" />
<typeAlias alias="Student" type="com.lsm.domain.Student" />
<resultMap class="Teacher" id="teacherBasicResultMap">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="subject" column="subject"/>
</resultMap>
<!-- 下面这个resultMap中有个students属性,这个结果映射继承自上面的结果映射由于有了继承,结果映射可以任意扩展-->
<resultMap class="Teacher" id="teacherWithTeacherResultMap" extends="teacherBasicResultMap">
<result property="students" column="id" select="getStudentsByTeacherId"/>
</resultMap>
<!-- 这个查询中使用到了上面定义的结果映射,从而决定了查询出来的Teacher中关联出相关的students,在student.xml中配置相似,不再注释。-->
<select id="getTeachers" resultMap="teacherWithTeacherResultMap">
<!--[CDATA[ select * from teacher ]]-->
</select>
<select id="getStudentsByTeacherId" resultClass="Student">
<!--[CDATA[ select s.* from student s,student_teacher st where s.id=st.studentid and st.teacherid=#value# ]]-->
</select>
</sqlMap>
package com.lsm.domain;
import java.util.List;
public class Teacher {
private int id;
private String name;
private String subject;
private List students; //注意这里有个List类型的students,表示一个老师对应多个学生
public List getStudents() {
return students;
}
public void setStudents(List students) {
this.students = students;
}
//省略掉其他的getter and setter
}
这里将查询teacher和student的<select>混合在一个文件中了,不如分开清晰。《iBatis2学习笔记:多对多映射(双向) 》中的例子比较好。
4550

被折叠的 条评论
为什么被折叠?



