默认:单个、列表
默认单个对象对应一个Map或实体
多条数据自动装进一个List
com.jerry.mapper.TestMapper.java
// 查询单个结果直接返回 Map<String, Object>
Map<String, Object> selectById(Long id);
//查询结果列表返回 List<Map<String, Object>>
List<Map<String, Object>> selectList(Map<String, Object> paramsMap);
com.jerry.mapper.TestMapper.xml
要map直接设置resultType即可。要list返回多个对象自动就是list,只要设置list里的对象类型即可。
<select id="selectById" resultType="map" parameterType="java.lang.Long">
select *
from test_table as tt
where 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集合。
@MapKey("id")
Map<Long, Map<Long, Integer>> selectCollection();
返回 Pair
虽然这里接收是用的Pair<Long, Integer>,但mybatis返回实际还是Pair<Integer, Long>,因为id字段在表中int,而统计结果collection默认Long
这会导致一个问题,后续我想再对 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>