如何使用mybatis返回Map<String, List<Object>>

问题描述 投票:0回答:1
这是gpt写的代码,但这不能返回我想要的,我希望这个函数返回一个Map类型的数据

,字符串是类别名称

<resultMap id="articles" type="com.toc.content.pojo.Article"> <result column="title" property="title" /> <result column="content" property="content" /> <result column="state" property="state"/> </resultMap> <resultMap id="CategoryArticleMap" type="java.util.HashMap"> <id column="category_name" property="key"/> <collection property="value" ofType="com.toc.content.pojo.Article" resultMap="articles"/> </resultMap> <select id="getCategoryArticlesMap" resultMap="CategoryArticleMap"> select c.category_name, a.title, a.content, a.state from category c left join article a on c.id = a.category_id where c.category_name is not null order by c.category_name </select>
在我的文章Dao.java中

@MapKey("category_name") Map<String, List<Article>> getCategoryArticlesMap();
我想从 json 获取这种类型

{ "art":[ {"title":"xxx", "author":"yyy" }, {"title":"ppp", "author":"ssy" }, ], }
    
java sql json spring mybatis
1个回答
0
投票
MyBatis 无法直接将结果映射到如此复杂的

java.util.Map

,不幸的是。

如果结果必须是

Map

,您可以告诉 MyBatis 返回 
List
Map
 并在 Java 代码中转换它。

import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.ibatis.annotations.Select; public interface Mapper { @Select(""" select c.category_name, a.title, a.author from category c left join article a on c.id = a.category_id where c.category_name is not null order by c.category_name """) List<Map<String, Object>> selectMaps(); default Map<String, List<Article>> getCategoryArticlesMap() { return selectMaps().stream().collect(Collectors.groupingBy(m -> (String) m.get("category_name"), Collectors.mapping(m -> new Article((String) m.get("title"), (String) m.get("author")), Collectors.toList()))); } }
请注意,某些数据库以大写形式返回列名称。


仅供参考,如果你定义了 POJO,MyBatis 可以直接映射结果。

import java.util.List; public class CategoryWithArticles { private String categoryName; private List<Article> articles; public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public List<Article> getArticles() { return articles; } public void setArticles(List<Article> articles) { this.articles = articles; } }
映射器看起来像这样。

<resultMap type="test.Article" id="articleRM"> <id property="title" column="title" /> <result property="author" column="author" /> </resultMap> <resultMap type="test.CategoryWithArticles" id="beanRM"> <id property="categoryName" column="category_name"/> <collection property="articles" resultMap="articleRM" /> </resultMap> <select id="selectBeans" resultMap="beanRM"> select c.category_name, a.title, a.author from category c left join article a on c.id = a.category_id where c.category_name is not null order by c.category_name </select>
这是映射器方法签名。

List<CategoryWithArticles> selectBeans();
    
© www.soinside.com 2019 - 2024. All rights reserved.