Return map in mybatis

Time:2019-10-18

In mybatis, we usually use it as follows:

  • Return a result
User selectOne(User user);
select id,username,telphone from user where telphone=#{telphone} and password = #{password}
  • Return multiple results (in fact, this is the same as the above, just the control of query conditions)
List selectList(User user);
select id,username,telphone from user

We just need toresultTypeChange tojava.util.HashMap, this will generate the following

Map selectList(User user);
select id,username,telphone from user where telphone=#{telphone} and password = #{password}

As a result, the attribute name of the user class is key and the attribute value is value.

Of course, you can also find multiple records and put this map in the list.

List selectList(User user);
select id,username,telphone from user

But sometimes we want this kind of result, what should we do?

{
    "01":{
        username:"zhangsan",
        telphone:"13000000000"
    }
}

That is, we need to customize a map.In this way, there are two solutions:

1. Use notes

@MapKey("id")
Map getUserInMap();
select id,username,telphone from user where telphone=#{telphone} and password = #{password}

The value of @ mapkey is a property of user object.

2. Write in the XML file

HashMap getUserInMap();
SELECT id as 'key', * as 'value', id,username,telphone from user where telphone=#{telphone} and password = #{password}

Of course, if there are more than one of the above two methods, it will also be list.

Form

Recommended Today

How to check the package according to the command in CentOS

In our work, we often encounter that we want to use a command machine that is not installed, but we don’t know which package the command is in (source compilation is not covered in this article). Here is a rather stupid method to help us solve this problem. Explain:Blue = command name Light green = […]