In Mybatis, we often use such as 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>
- Return multiple results (and in fact the top, in that it is the only control query)
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 on top of the resultType
change java.util.HashMap
, so it will generate 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>
This result is to say, the User class attribute-called key, attribute value value.
Of course, you can also check out the many records, this Map into a 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, how to do it?
{
"01":{
username:"zhangsan",
telphone:"13000000000"
}
}
This is what we want to customize a Map <String, User>, this is the case, there are two solutions:
1. Notes
@MapKey("id")
Map<String,User> getUserInMap();
<!--xml和之前写法一样-->
<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 a property @MapKey is written User objects
2. Write on 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 you check out a number of words will be List