Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MyBatis: How to return a map of lists?

Tags:

java

mybatis

I have Googled this until I was blue in the face and could not find an answer. How can I configure MyBatis to return a Map of Lists ?

ie

HashMap<String, List<Foo>>

For example, if I had a query that returned all the orders for all my customers and I wanted to get it to return a Map containing a list of the orders keyed by the customer id.

EDIT

I found a way to do it by writing a custom ResultHandler, but would rather have MyBatis do it for me much like Hibernate does with either mapping or annotations.

Thanks.

like image 520
AfterWorkGuinness Avatar asked Feb 05 '14 15:02

AfterWorkGuinness


People also ask

What is the difference between MyBatis query map and resultmap?

So in fact, every query mapping of MyBatis is ResultMap, but when the return type attribute we provide is resultType, MyBatis automatically assigns the corresponding value to the attribute of the object specified by resultType. When the return type we provide is resultMap, because Map can not represent the domain model very well, we need ourselves.

What is the return type of MyBatis query?

Keywords: Attribute Mybatis Java Session In MyBatis, when a query is select ed for mapping, the return type can be either resultType or resultMap, which is a direct representation of the return type, while resultMap is a reference to the external ResultMap, but resultType and resultMap cannot exist simultaneously.

What should I add to a MyBatis result?

The type of the result. MyBatis can usually figure this out, but it doesn't hurt to add it to be sure. MyBatis allows any simple type to be used as the key, including Strings. If you are expecting multiple generated columns, then you can use an Object that contains the expected properties, or a Map.

How does MyBatis assign the value to a query object?

MyBatis's own judgment is to compare the field of the query or its corresponding alias with the attributes of the returned object. If it matches and the type matches, MyBatis assigns the value to it. In the corresponding resultMap above, a blog attribute is associated, and its corresponding JAVA type is Blog.


1 Answers

The easiest thing I have found was creating a new POJO and putting the id and list of objects in there.

StringFoo.java

public class StringFoo {
    String name;
    List<Foo> foos;
}

Mapper.java

List<StringFoo> findFoo(@Param("id") Long id);

Mapper.xml

<resultMap id="FooResultMap" type="com.package.StringFoo">
    <result property="name" column="name"/>
    <collection property="foo" resultMap="FooMapORJavaType"/>
</resultMap>
<select id="findFoo" resultMap="FooResultMap"></select>
like image 114
John Szafraniec Avatar answered Nov 07 '22 22:11

John Szafraniec