Mybatis中collection和association的使用区别

1. 关联-association
2. 集合-collection

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

  association-一对一 ,人和身份证的关系

  <mapper namespace="com.glj.mapper.PersonMapper">

  <resultMap type="com.glj.poji.Person" id="personMapper">
  <id property="id" column="id"/>
  <result property="name" column="name"/>
  <result property="age" column="age"/>
  <association property="card" column="card_id"  select="selectPersonById"  javaType="com.gl.Card">  
     <id property="id" column="id"/>
      <result property="name" column="name"/>
    <result property="age" column="age"/>
  </association>
  </resultMap>
<select id="selectPersonById" parameterType="int" resultMap="personMapper">
select * from tb_person where id = #{id}
</select>
 

collection 一对多和association的多对一关系

学生和班级的一对多的例子

<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"/>
<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
<collection property="students" ofType="com.gl.pojo.Student"
column="id" javaType="ArrayList"
fetchType="lazy" select="com.gl.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>

猜你喜欢

转载自www.cnblogs.com/zwj-I-zm/p/9297661.html