Mybatis collection 组装数据
通过sql语句查出来的数据如下图所示:
student_id=860的有两条,861的有两条。现在我需要下面的这样一个结构:
用一条sql语句就能实现了,不需要再到代码中遍历处理了。
<resultMap id="categoryScoreMap" type="java.util.Map">
<id property="studentId" column="studentId"/>
<collection property="categorys" javaType="java.util.ArrayList" ofType="java.util.Map">
<id property="category" column="category"/>
<result property="name" column="name"/>
<result property="score" column="score"/>
</collection>
</resultMap>
<select id="categoryScoreStatistics" resultMap="categoryScoreMap">
SELECT
a.student_id studentId,
b.category,
c.name,
sum( a.score ) score
FROM
s_student_job_response a
JOIN t_question b ON a.question_id = b.id
JOIN d_category c ON b.category = c.id
WHERE
a.job_id = #{jobId}
AND a.student_id IN
<foreach collection="studentIds" item="item" index="index" open="(" separator="," close=")">
#{item}
</foreach>
GROUP BY
a.student_id,
b.category
ORDER BY
a.student_id,
b.category
</select>
返回来的类型是Map集合,尤其注意collection的写法。
如果返回来的结果是Java代码中定义的某个对象。对象中又有一个字段是List集合,例如:
那么代码就可以这样写了:
特别注意圈红色框的地方。
---------------------
作者:猿梦之秃
来源:CSDN
原文:https://blog.csdn.net/huangshuangda/article/details/108815489?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163098342616780271532267%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=163098342616780271532267&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v29-1-108815489.pc_search_ecpm_flag&utm_term=mybatis+collection+%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F&spm=1018.2226.3001.4187
版权声明:本文为上一个作者原创文章,转载请附上博文链接请询问猿梦之秃!