- 關(guān)聯(lián)-association
- 集合-collection
association是用于一對一和多對一碍讨,而collection是用于一對多的關(guān)系
舉例:
學(xué)生和班級
pojo
public class Clazz implements Serializable{
private Integer id;
private String code;
private String name;
//班級與學(xué)生是一對多的關(guān)系
private List<Student> students;
//省略set/get方法
}
public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
//學(xué)生與班級是多對一的關(guān)系
private Clazz clazz;
//省略set/get方法
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.glj.mapper.ClazzMapper">
<select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
select * from tb_clazz where id = #{id}
</select>
<resultMap type="com.glj.pojo.Clazz" id="clazzResultMap">
<id property="id" column="id"/>
<result property="code" column="code"/>
<result property="name" column="name"/>
<collection property="students" ofType="com.glj.pojo.Student"
column="id" javaType="ArrayList"
fetchType="lazy" select="com.glj.mapper.StudentMapper.selectStudentByClazzId">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
</collection>
</resultMap>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.glj.mapper.StudentMapper">
<select id="selectStudentById" parameterType="int" resultMap="studentResultMap">
select * from tb_clazz c,tb_student s where c.id = s.id and s.id = #{id}
</select>
<select id="selectStudentByClazzId" parameterType="int" resultMap="studentResultMap">
select * from tb_student where clazz_id = #{id}
</select>
<resultMap type="com.glj.pojo.Student" id="studentResultMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<association property="clazz" javaType="com.glj.pojo.Clazz">
<id property="id" column="id"/>
<result property="code" column="code"/>
<result property="name" column="name"/>
</association>
</resultMap>
</mapper>