,字符串是类别名称
<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.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())));
}
}
请注意,某些数据库以大写形式返回列名称。
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();