Mybatis中collection和association的使用区别

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>

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值