Mybatis返回值封装在Map集合中

数据库表:

CREATE TABLE `products` (
  `prod_id` char(10) COLLATE utf8_unicode_ci NOT NULL,
  `vend_id` char(10) COLLATE utf8_unicode_ci NOT NULL,
  `prod_name` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `prod_price` decimal(8,2) NOT NULL,
  `prod_desc` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`prod_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

映射文件:

<?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.heiketu.testpackage.mapper.ProductsMapper">

<select id="getResultUseMap" resultType="map">
    SELECT * FROM Products WHERE prod_id = #{prod_id}
</select>
</mapper>
/**
引入了lombok插件
*/
@Setter
@Getter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Products {
    private String prodId;
    private String vendId;
    private String prodName;
    private BigDecimal prodPrice;
    private String prodDesc;
}

映射接口:

public interface ProductsMapper {
    //结果集以Map形式返回
    public Map<String,Object> getResultUseMap(@Param("prod_id") String productId);
}

测试代码:

SqlSession sqlSession = null;

try {
    String configFile = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(configFile);
    SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
    sqlSession = build.openSession();

    //以Map形式返回
    ProductsMapper mapper = sqlSession.getMapper(ProductsMapper.class);
    Map<String, Object> useMap = mapper.getResultUseMap("BR03");

    //返回形式是key=字段名,value=字段的值
    System.out.println(useMap);

} catch (IOException e) {
    e.printStackTrace();
}finally {
    sqlSession.close();
}

结果:

{vend_id=BRS01, prod_desc=18 inch teddy bear, comes with cap and jacket, prod_price=11.99, prod_id=BR03, prod_name=18 inch teddy bear}

总结:
mybatis映射返回值封装成Map需要在映射文件中的resultType属性值设置为map(map为mybatis默认设置的Map集合类别名).
封装的结果结构为: {key=字段名,value=字段的值,key=字段名,value=字段的值...}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值