一、返回Map处理
在Mybatis中,支持返回值为Map<K,V>的操作,如果需要返回值为Map时,在Mapper接口的该方法上添加@MapKey(value="属性名")注解,则会把结果集按照Map返回,并且key为@MapKey上设置的属性。
二、案例
mapper映射文件:
<?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.my.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.my.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="real_name" jdbcType="VARCHAR" property="realName" />
<result column="sex" jdbcType="CHAR" property="sex" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="note" jdbcType="VARCHAR" property="note" />
<result column="position_id" jdbcType="INTEGER" property="positionId" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, real_name, sex, mobile, email, note, position_id
</sql>
<select id="select" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from user
</select>
</mapper>
mapper接口:
public interface UserMapper {
@MapKey("id")
Map<Integer,User> select();
}
测试代码:
public class MybatisTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
String resource = "mybatis-config.xml";
//1.使用mybatis的工具读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.创建sqlSessionFactory
sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
inputStream.close();
}
/**
* 测试返回值Map
*/
@Test
public void testMap() {
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
Map<Integer, User> map = userMapper.select();
System.out.println(map);
sqlSession.close();
}
}
三、补充说明
1.返回值是Map<K,V>时,默认情况下,V只能是复杂对象,在映射文件中的select标签中的resultMap属性应该为该复杂对象的映射结果集。
2.最好不要使用返回值是Map<K,V>,因为不易维护,且可以自己进行List转Map的处理,Mybatis底层也是通过把List转为Map。