Mybatis中collection和association的使用区别

tech2025-05-19  10

1. 关联-association

用于一对一和多对一

示例:

@Data public class ZSJC1 { private int id; private String name; @TableField(exist = false) private ZSJC2 zsjc2; } @Data public class ZSJC2 { private int id; private String name; private String type; @TableField("c1_id") private int c1Id; } <!--resultMap 自定义封装规则--> <!-- id:唯一id,方便引用 type:自定义规则的java类型 --> <resultMap id="BaseMap" type="com.xx.xx.entiy.ZSJC1"> <!-- id 主键的封装规则,底层会有优化 column 数据库中字段 property javaBean中的字段 --> <id column="id" property="id"/> <result column="name" property="name"/> <!-- association处理has-a关系 --> <association property="zsjc2" javaType="com.xx.xx.entiy.ZSJC2"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="type" column="type"/> <result property="c1Id" column="c1_id"/> </association> </resultMap> <select id="get" resultMap="BaseMap"> SELECT * FROM zsj_c1 a LEFT JOIN zsj_c2 b ON a.id=b.c1_id </select>

2. 集合-collection

用于一对多的关系

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

import java.io.Serializable;

import java.util.List;

 

public class Clazz implements Serializable{

private Integer id;

private String code;

private String name;

        //班级与学生是一对多的关系

private List<Student> students;

//省略set/get方法

}

import java.io.Serializable;

 

public class Student implements Serializable {

private Integer id;

private String name;

private String sex;

private Integer age;

        //学生与班级是多对一的关系

private Clazz clazz;

//省略set/get方法

}

 

<!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"/>

<!-- property: 指的是集合属性的值, ofType:指的是集合中元素的类型 -->

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

 

最新回复(0)