首页 » SEO优化 » php返回map技巧_Mybatis 查询结果返回 MapListPair

php返回map技巧_Mybatis 查询结果返回 MapListPair

访客 2024-12-06 0

扫一扫用手机浏览

文章目录 [+]

<select id="selectById" resultType="map" parameterType="java.lang.Long">select from test_table as ttwhere tt.id = #{id}</select><select id="selectList" resultType="map" parameterType="map">select from test_table as tt</select>返回 Map凑集

查询收藏按 article_id 分组统计。
返回类型HashMap。
如果默认类型不符合需求,可以添加 一个resultMap来定义一下。

<!-- 按文章主键 article_id 分组统计收藏量 --> <resultMap id="myMap" type="Map" > <result property="id" javaType="Long" column="id"/> <result property="collection" javaType="Integer" column="collection"/> </resultMap> <select id="selectCollection" resultMap="myMap"> SELECT c.article_id AS id, Count(c.id) AS collection FROM collections AS c GROUP BY c.article_id </select>

在接口上添加 @MapKey("id")指定key,常日便是用主键。
返回实现Map凑集。

php返回map技巧_Mybatis 查询结果返回 MapListPair

@MapKey("id") Map<Long, Map<Long, Integer>> selectCollection();返回 Pair

虽然这里吸收是用的Pair<Long, Integer>,但mybatis返回实际还是Pair<Integer, Long>,由于id字段在表中int,而统计结果collection默认Long

php返回map技巧_Mybatis 查询结果返回 MapListPair
(图片来自网络侵删)

这会导致一个问题,后续我想再对 pair.getKey()转换类型时,它会理外不是人。

以是精确的该当是利用与Mybatis返回类型一至的变量来吸收。
这样后续类型转换时才不会报错。

List<Pair<Integer, Long>> selectCollection(); // 正常

<select id="selectCollection" resultType="javafx.util.Pair"> SELECT c.article_id AS id, Count(c.id) AS collection FROM collections AS c GROUP BY c.article_id </select>

标签:

相关文章