association和collection区别

作者: 佐半边的翅膀 | 来源:发表于2020-03-30 15:22 被阅读0次
  1. 关联-association
  2. 集合-collection

association是用于一对一和多对一,而collection是用于一对多的关系

举例:
学生和班级
pojo
public class Clazz implements Serializable{
private Integer id;
private String code;
private String name;
//班级与学生是一对多的关系
private List<Student> students;
//省略set/get方法
}
public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
//学生与班级是多对一的关系
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>

相关文章

网友评论

    本文标题:association和collection区别

    本文链接:https://www.haomeiwen.com/subject/epsvuhtx.html