Search code examples
javamybatisspring-mybatismybatis-mappermybatis-sql

Getting Map<Long, List<Object>> using MyBatis


Here is my method, I need to get a Map<Long, List<CMBill>>:

@Mapper
public interface CMBillMapper {

    @MapKey("groupId")
    Map<Long, List<CMBill>> getCMInvoicesByIdListSQL(@Param("invoiceIds") Set<Long> invoiceIds);
}

Here is MyBatis xml config, which configures this map.

<?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="ru.example.CMBillMapper">
    <resultMap id="CMBillResult" type="CMBill">
        <result property="id" column="id"/>
        <result property="groupId" column="group_id"/>
        <result property="clientId" column="client_id"/>
        <result property="paidAmount" column="paid_amount"/>
        <result property="amount" column="amount"/>
        <result property="currency" column="currency"/>
        <result property="status" column="status"/>
    </resultMap>
    <select id="getCMInvoicesByIdListSQL" resultMap="CMBillResult">
        select it.group_id    as group_id,
               it.id          as id,
               it.client_id   as receiver_id,
               it.status      as invoice_status,
               it.amount      as amount,
               it.currency    as currency,
               it.paid_amount as paid_amount,
               if.type        as if_type,
               if.code        as if_code,
               if.val         as if_val
        from cm_invoice_tab it
                 left join cm_inv_group_field_tab if
                           on if.group_id = it.group_id
        where it.group_id in (#{invoiceIds})
    </select>
</mapper>

But the result of mapper is Map<Long, CMBill>, and I need another one. How to rewrite my mapper for getting result which I need?


Solution

  • In this case, it is recommended that you directly query and obtain List, and then group the group_id after obtaining the result set.