Detailed explanation of @ mapkey annotation in mybatis

Mybatis was originally ibatis, but now it has separated from the Apache foundation. The new official website is http://www.mybatis.org/ 。

Before studying the source code of mybatis, I didn't know the wonderful use of this annotation, but when I saw the parameter parsing, there was an annotation, so I learned that when we return such types as map < string, map < string, Object > >, it is often difficult for us to do so, because there may be data from multiple tables, so we can't build another model.

Then we can use this annotation

Obviously, this annotation is used on the method. The specific usage is to set the key of the external map. In this way, we can query very complex results without creating a new entity

PS: let's take a look. Mybatis uses the @ mapkey annotation to receive multiple query records into the map, so as to easily obtain the value of the field with the get () method

Demand scenario:

Find out several pieces of data from the database in batch, including ID and name fields. It is hoped that the results can be received directly with map, and then through map Get (ID) makes it easy to get the value of name.

Question:

If the following code is used, an error will be reported if there are multiple query results, because mybatis saves the results in the form of ("Id": 123), ("name": "Jack") in the map. Therefore, if a record including ID and name is returned, there is no problem; If multiple records are returned, that is, there are multiple ("Id": 123), ("Id": 124), mybatis is stupid and doesn't know how to deal with it.

The solution is to use a map outside:

Then, add a comment on the Dao method:

This annotation indicates that the key of the outermost map is the value with the field name "Id" in the query result.

Mapper. The configuration in XML is as follows:

The above is a detailed explanation of the use of @ mapkey annotation in mybatis introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>