[转] Mybatis中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类

 1 package com.glj.pojo;
 2  
 3 import java.io.Serializable;
 4 import java.util.List;
 5  
 6 public class Clazz implements Serializable{
 7     private Integer id;
 8     private String code;
 9     private String name;
10         //班级与学生是一对多的关系
11     private List<Student> students;
12 //省略set/get方法
13 }
 1 package com.glj.pojo;
 2  
 3 import java.io.Serializable;
 4  
 5 public class Student implements Serializable {
 6     private Integer id;
 7     private String name;
 8     private String sex;
 9     private Integer age;
10         //学生与班级是多对一的关系
11     private Clazz clazz;
12 //省略set/get方法
13 }

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

ClazzMapper.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper
 3     PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.glj.mapper.ClazzMapper">
 6     <select id="selectClazzById" parameterType="int" resultMap="clazzResultMap">
 7         select * from tb_clazz where id = #{id}
 8     </select>
 9     <resultMap type="com.glj.pojo.Clazz" id="clazzResultMap">
10         <id property="id" column="id"/>
11         <result property="code" column="code"/>
12         <result property="name" column="name"/>
13         <!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->
14         <collection property="students" ofType="com.glj.pojo.Student"
15         column="id" javaType="ArrayList"
16         fetchType="lazy" select="com.glj.mapper.StudentMapper.selectStudentByClazzId">
17             <id property="id" column="id"/>
18             <result property="name" column="name"/>
19             <result property="sex" column="sex"/>
20             <result property="age" column="age"/>
21         </collection>
22     </resultMap>
23 </mapper>

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


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

附上一张mybatis的类型别名图

原文出处    https://199604.com/709

原文地址:https://www.cnblogs.com/binghuaZhang/p/13784889.html