Mybatis从入门到精通——返回Map处理(17)

一、返回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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值