Return to Map in Mybatis

Keywords: Java Attribute xml Mobile

In Mobile, we usually use the following:

  • Returns a result
User selectOne(User user);
<select id="selectOne"  parameterType="cn.lyn4ever.entity.User"  resultType="cn.lyn4ever.entity.User">
       select id,username,telphone from user where telphone=#{telphone} and password = #{password}
    </select>
  • Returns multiple results (in fact, as above, it's just a control of the query conditions)
List<User> selectList(User user);
<select id="selectOne"  parameterType="cn.lyn4ever.entity.User"  resultType="cn.lyn4ever.entity.User">
       select id,username,telphone from user
    </select>

We just need to change the resultType above to java.util.HashMap, which generates the following

Map selectList(User user);
<select id="selectOne"  parameterType="cn.lyn4ever.entity.User"  parameterType="cn.lyn4ever.entity.User"   resultType="java.util.HashMap">
       select id,username,telphone from user where telphone=#{telphone} and password = #{password}
    </select>

The result is that the attribute of the User class is named key and the value of the attribute is value.

Of course, you can also find multiple records and put the Map in the List.

List<Map> selectList(User user);
<select id="selectOne"  parameterType="cn.lyn4ever.entity.User"  resultType="java.util.HashMap">
       select id,username,telphone from user
    </select>

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

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

That is to say, we need to customize a Map < String, User>, so there are two solutions:

1. Use annotations

@MapKey("id")
Map<String,User> getUserInMap();
<!--xml It's the same as before.-->
<select id="getUserInMap" parameterType="cn.lyn4ever.entity.User"   resultType="User">
   select id,username,telphone from user where telphone=#{telphone} and password = #{password}
</select>

The value of @MapKey writes about an attribute of the User object

2. Write in the xml file

 HashMap<String,Object> getUserInMap();
<select id="getUserInMap" parameterType="cn.lyn4ever.entity.User"   resultType="java.util.HashMap">
SELECT id as 'key', * as 'value', id,username,telphone from user where telphone=#{telphone} and password = #{password}
</select>

Of course, the above two methods, if found out is more than one, will also be in the form of a List.

Posted by ashleek007 on Sat, 05 Oct 2019 15:11:18 -0700