Use Mybatis's @MapKey annotation to return Map collection cases

1. Usage scenarios of Mybatis@MapKey annotation

When performing multi-value queries, the method return type is usually set to the Map<String,Object> type. Mybatis provides us with another solution, which is to save the query results in the Map in the form of KV. This implementation method Just mark the method as @Mapkey.

2. Code

@Mapper
public interface TbUserInfoMapper {

    // 使用多个userCode查询多个用户信息
    @MapKey("userCode")
    public Map<String, TbUserInfo> findUserInfoByCode(List<String> userCode); 

}

Interface implementation:

<select id="findUserInfoByCode" resultMap="userInfoResultMap">
    SELECT userCode, userName
	FROM tbl_user_sub where userCode in
	<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> 
            #{item} 
	</foreach> and PARTYTYPE=001;
</select>

Instructions for using foreach loop traversal:
Basic syntax of foreach: The main attributes in the label body are item, index, collection, open, separator, close

  • item: Alias ​​when iterating elements in the collection
  • index: the index of the elements in the collection when iterating
  • open: Indicates what to start with
  • separator: represents the separator during each iteration
  • close is commonly used in where statements to indicate what to end with.

The most critical and most error-prone thing when using foreach is the collection attribute. This attribute must be specified, but in different situations, the value of this attribute is different. There are three main situations:

  • If a single parameter is passed in and the parameter type is a List, the collection attribute value is list.
  • If a single parameter is passed in and the parameter type is an array array, the attribute value of the collection is array.
  • If there are multiple parameters passed in, we need to encapsulate them into a Map. Of course, a single parameter can also be encapsulated into a map. In fact, if you pass in parameters, it will also be encapsulated in MyBatis. It becomes a Map, and the key of the map is the parameter name, so at this time, the collection attribute value is the key of the passed in List or array object in its own encapsulated map.

Regarding the last one, let’s take a look at the official statement:

Note: You can pass a List instance or array as a parameter object to MyBatis. When you do this, MyBatis will automatically wrap it in a Map and use the name as the key. List instances will have "list" as the key, and array instances will have "array" as the key.

Guess you like

Origin blog.csdn.net/amosjob/article/details/100136361