理解mybaitis中的association和collection的区别


最近一直把collection和association弄混,所以为了增强自己的记忆,就撸一个关系出来算是总结罢了


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

比如同时有User.java和Card.java两个类

User.java如下:

public class User{

private Card card_one;

private List<Card> card_many;

}

 

在映射card_one属性时用association标签, 映射card_many时用collection标签.

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

下面就用一些例子解释下吧

association-一对一

人和身份证的关系

下面是pojo

下面是mapper和实现的接口

PersonMapper.xml 还使用association的分步查询。

同理多对一,也是一样

只要那个pojo出现private Card card_one;

即使用association


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

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

pojo类

ClazzMapper使用到了集合-collection 即为一对多,一个班级面对多个学生

 

<?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>

StudentMapper则是与班级为多对一关系,所以使用了关联-association


嗯,希望我以后又不记得二者的关系时,能感谢现在总结的自己


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM