在Mybatis中,我们通常会像下边这样用:
返回一个结果
User selectOne(User user);
select id,username,telphone from user where telphone=#{telphone} and password = #{password}
返回多个结果(其实这个和上边一样,只不过是查询条件的控制而已)
List selectList(User user);
select id,username,telphone from user
我们只要将上边的resultType改为java.util.HashMap,这会有生成下边这样
Map selectList(User user);
select id,username,telphone from user where telphone=#{telphone} and password = #{password}
上这结果就是说,以User类的属性名为key,属性值为value。
当然,也可以查出来多条记录,将这个Map放进List中
List selectList(User user);
select id,username,telphone from user
但是有时候我们想要这种结果,怎么办呢?
{
"01":{
username:"zhangsan",
telphone:"13000000000"
}
}
也就是我们要自定义一个Map,这样的话,有以下两种解决方法:
1.使用注解
@MapKey("id")
Map getUserInMap();
select id,username,telphone from user where telphone=#{telphone} and password = #{password}
这个@MapKey的value写的就是User对象的一个属性
2.在xml文件中写上
HashMap getUserInMap();
SELECT id as 'key', * as 'value', id,username,telphone from user where telphone=#{telphone} and password = #{password}
当然以上这两种方法,如果查出来是多条的话也会是List的形式
到此这篇关于Mybatis中返回Map的实现的文章就介绍到这了,更多相关Mybatis中返回Map内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!