根据条件查询list中对应字段信息_神烦,老大让讲一下Mybatis中强大的resultMap

resultType

resultType可以把查询结果封装到pojo类型中,但必须pojo类的属性名和查询到的数据库表的字段名一致。
如果sql查询到的字段与pojo的属性名不一致,则需要使用resultMap将字段名和属性名对应起来,进行手动配置封装,将结果映射到pojo中

resultMap

resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。3cd0d77a00448344b4153c9544a974ac.png

先在Mapper文件中,配置基本的sql语句

        <select id="queryOrderAll" resultMap="orderResultMap">        SELECT id, user_id,        number,        createtime, note FROM `order`    select>

配置resultMap标签,映射不同的字段和属性名

        <resultMap type="order" id="orderResultMap">                                <id property="id" column="id" />                <result property="userId" column="user_id" />        <result property="number" column="number" />        <result property="createtime" column="createtime" />        <result property="note" column="note" />    resultMap>

结果就可以封装到pojo类型中

使用resultMap进行关联查询
一对一查询

一对一数据模型:订单用户
一个订单信息只会是一个人下的订单,所以从查询订单信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的订单信息则为一对多查询,因为一个用户可以下多个订单。6206a456bfb2a1af14c9cf50558a75d8.png

  • 改造pojo类
    在订单类中添加User属性,User属性是一个引用类型,用于存储关联查询的用户信息,因为关联关系是一对一,所以只需要添加单个属性即可a6aec3755f6872a538abb258d74f974d.png

  • 配置Mapper.xml配置文件
    OrderMapper.xml
    先使用id和result属性,映射order类的结果集,然后在使用association映射关联对象User的结果集

<resultMap type="order" id="orderUserResultMap">    <id property="id" column="id" />    <result property="userId" column="user_id" />    <result property="number" column="number" />    <result property="createtime" column="createtime" />    <result property="note" column="note" />                    <association property="user" javaType="user">                <id property="id" column="user_id" />        <result property="username" column="username" />        <result property="address" column="address" />    association>resultMap><select id="queryOrderUserResultMap" resultMap="orderUserResultMap">    SELECT    o.id,    o.user_id,    o.number,    o.createtime,    o.note,    u.username,    u.address    FROM    `order` o    LEFT JOIN `user` u ON o.user_id = u.idselect>

测试

@Testpublic void testQueryOrderUserResultMap() {    // mybatis和spring整合,整合之后,交给spring管理    SqlSession sqlSession = this.sqlSessionFactory.openSession();    // 创建Mapper接口的动态代理对象,整合之后,交给spring管理    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);    // 使用userMapper执行根据条件查询用户,结果封装到Order类中    Listlist = userMapper.queryOrderUserResultMap();    for (Order o : list) {        System.out.println(o);    }    // mybatis和spring整合,整合之后,交给spring管理    sqlSession.close();}

结果

acfbc91343ab766f220d8fe268800a82.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值