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.
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With