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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM