mybatis集合映射association与collection

发布于:2025-03-21 ⋅ 阅读:(24) ⋅ 点赞:(0)

官方文档:MyBatis的一对多关联关系

一、用途

一对一:association

一对多:collection

二、association

比较容易理解,可参考官方文档

三、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.lyy.WaterMapper">
    <resultMap id="BaseResultMap" type="com.lyy.WaterVO">
        <id property="id" column="id" jdbcType="BIGINT"/>
        <result property="name" column="name"/>
        <collection property="solidList"
                    javaType="list"
                    ofType="com.lyy.SolidVO"
                    select="selectSolidList"
                    column="id">
        </collection>
        <collection property="gasList"
                    javaType="list"
             ofType="com.lyy.GasVO"
                    select="selectGasList"
                    column="id">
        </collection>
    </resultMap>

    <resultMap id="solidList" type="com.lyy.SolidVO">
        <collection property="solidList" javaType="list"
                    ofType="com.lyy.SolidVO"
                    select="selectSolidList" column="id">
        </collection>
    </resultMap>

    <resultMap id="gasList" type="com.lyy.GasVO">
        <collection property="gasList" javaType="list"
                    ofType="com.lyy.GasVO"
                    select="selectGasList" column="id">
        </collection>
    </resultMap>

    <select id="selectSolidList" resultMap="solidList">
        SELECT id,name,num
        FROM water w
        left join solid s on w.id=s.id
        WHERE w.id = #{id}
    </select>

    <select id="selectGasList" resultMap="gasList">
        SELECT id,name,size
        FROM water w
        left join gas g on w.id=g.id
        WHERE w.id = #{id}
    </select>
    //最终的使用
    <select id="getInfo" resultMap="BaseResultMap">
        SELECT *
        FROM water w
        left join c on c.id =w.id
        where w.id=#{id}
    </select>
</mapper>
实体类
public class SolidVO{
    Long id;
    String name;
    Long  num;
}

public class GasVO{
    Long id;
    String name;
    Long  size;
}

public class WaterVO{
    Long id;
    String name;
    List<SolidVO> solidList;
    List<GasVO> gasList;
}

注意:

1、column="id" 将当前查询结果中的ID作为参数,传递给子查询selectSolidList

2、几个对应关系

结果:

{
  "id": 30,
  "name": "盐酸",
  "solidList":[
    {
        "id": 1,
        "name": "xx",
        "num":"xx"
    },
     {
        "id": 5,
        "name": "xx",
        "num":"xx"
    },
  ],
 "gasList":[
    {
        "id": 4,
        "name": "xx",
        "size":"xx"
    },
     {
        "id": 5,
        "name": "xx",
        "size":"xx"
    },
  ]
      
}