MyBatis 查询结果映射为 HashMap:使用 ResultMap 实现集合参数查询
可以使用 MyBatis 的 ResultMap 来实现查询结果为 HashMap 的功能。以下是一个示例代码:
@Mapper
public interface MyMapper {
@Select("SELECT a, b FROM my_table WHERE c IN (#{list})")
@MapKey("a")
Map<String, String> queryData(@Param("list") List<String> list);
}
在上述代码中,queryData 方法接收一个参数 list,参数类型为 List<String>,表示查询条件中的集合参数。使用 IN 关键字可以将集合参数传递给 SQL 语句。@MapKey("a") 注解表示以字段 a 作为 HashMap 的 key。
在 Mapper 接口中使用 @Mapper 注解,表示该接口是 MyBatis 的 Mapper 接口。
然后在配置文件中配置 ResultMap:
<resultMap id="resultMap" type="java.util.HashMap">
<id property="a" column="a" />
<result property="b" column="b" />
</resultMap>
在配置文件中,使用 <resultMap> 标签定义一个 ResultMap,将查询结果的字段 a 和 b 映射到 HashMap 的 key 和 value。type 属性指定了 ResultMap 的类型。
最后,在配置文件中配置 Mapper 接口和 ResultMap 的映射关系:
<mapper namespace="com.example.MyMapper">
<select id="queryData" resultMap="resultMap">
SELECT a, b FROM my_table WHERE c IN (#{list})
</select>
</mapper>
在配置文件中,使用 <mapper> 标签指定了 Mapper 接口的命名空间,<select> 标签指定了查询语句,并通过 resultMap 属性将查询结果映射到 ResultMap。
这样,在调用 queryData 方法时,将会返回一个 HashMap,其中 key 为字段 a 的值,value 为字段 b 的值。
原文地址: https://www.cveoy.top/t/topic/lGtM 著作权归作者所有。请勿转载和采集!