1.数据库表结构
CREATE TABLE `dbl_t_person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`tel` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
`bdate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
2.测试数据
INSERT INTO `dbl_t`.`dbl_t_person`(`id`, `name`, `age`, `address`, `tel`, `bdate`) VALUES (1, '张三', 18, '成都', '18876372890', '1999-06-16');
INSERT INTO `dbl_t`.`dbl_t_person`(`id`, `name`, `age`, `address`, `tel`, `bdate`) VALUES (2, '李四', 18, '重庆', '17789938729', '2002-06-12');
INSERT INTO `dbl_t`.`dbl_t_person`(`id`, `name`, `age`, `address`, `tel`, `bdate`) VALUES (3, '王五', 17, '上海', '18719383379', '2003-11-19');
3.Mapper
@Mapper
public interface PersonMapper {
@MapKey("age")
Map<String, List<Person>> listPerson();
}
4.Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dbl.demo.dao.PersonMapper">
<resultMap id="result" type="java.util.Map">
<!-- 不可缺少 -->
<result column="age" property="age"></result>
<collection property="person" javaType="arrayList" ofType="com.dbl.demo.entity.Person">
<result property="id" column="id"></result>
<result property="age" column="age"></result>
<result property="name" column="name"></result>
<result property="tel" column="tel"></result>
<result property="bDate" column="bdate"></result>
<result property="address" column="address"></result>
</collection>
</resultMap>
<select id="listPerson" resultMap="result">
select * from dbl_t_person
</select>
</mapper>
5.返回结果
{17={person=[Person(id=3, name=王五, age=17, address=上海, tel=18719383379, bDate=Wed Nov 19 00:00:00 GMT+08:00 2003)], age=17}, 18={person=[Person(id=1, name=张三, age=18, address=成都, tel=18876372890, bDate=Wed Jun 16 00:00:00 GMT+08:00 1999), Person(id=2, name=李四, age=18, address=重庆, tel=17789938729, bDate=Wed Jun 12 00:00:00 GMT+08:00 2002)], age=18}}