Mybatis查询

  1. 返回实体类,必须指定返回类型, resultType不能省略,并且数据库字段名与实体类不一致会填充NULL,实体类我们一般都是驼峰,数据库字段一般都是下划线,所以在查询的时候可以起别名解决,属性填充本质上调用的是实体类的set方法,例如

    例如car_num就会变成 setCar_num实体类并没有这个方法,所以实体类这个变量就会为NULL

    <select id="selectCarById" resultType="com.powernode.mybatis.pojo.Car">
    select id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carTypefrom t_car where id = #{id}
    </select>
    
  2. 查询多条数据,例如List

    <!--虽然结果是List集合,但是resultType属性需要指定的是List集合中元素的类型。-->
    <select id="selectCarById" resultType="com.powernode.mybatis.pojo.Car">
    select id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carTypefrom t_car where id = #{id}
    </select>
    
  3. 用Map接受返回结果

    Map<String, Object> getUser(String account);
    
    <select id="getUser" resultType="map">
        select *
        from user
        where account = '${account}' or 1 = 1;
    </select>
    

    数据库为NULL的列不会查出来
    在这里插入图片描述

  4. 用Map来接受对象

    	@MapKey里面填写一个列名作为Map的key,value为User实体类,为空也会被查出来
        @MapKey("id")
        Map<String,Object> getUser();
    
        <select id="getUser" resultType="user">
            select *
            from user
        </select>
    

    在这里插入图片描述

  5. ResultMap结果映射
    查询结果的列名和java对象的属性名对应不上怎么办?
    第一种方式:as 给列起别名
    第二种方式:使用resultMap进行结果映射
    第三种方式:是否开启驼峰命名自动映射(配置settings),前提命名要规范,实体类全部使用驼峰命名,数据库字段用下划线命名

    mybatis:
      configuration:
        map-underscore-to-camel-case: true #开启驼峰映射
    
    /**
    * 查询所有Car,使用resultMap进行结果映射
    * @return
    */
    List<Car> selectAllByResultMap();
    
    <!--
    resultMap:
    id:这个结果映射的标识,作为select标签的resultMap属性的值。
    type:结果集要映射的类。可以使用别名。
    -->
    <resultMap id="carResultMap" type="car">
    <id property="id" column="id"/>
    <result property="carNum" column="car_num"/>
    <!--当属性名和数据库列名一致时,可以省略。但建议都写上。-->
    <!--javaType用来指定属性类型。jdbcType用来指定列类型。一般可以省略。-->
    <result property="brand" column="brand" javaType="string" jdbcType="VARC
    HAR"/>
    <result property="guidePrice" column="guide_price"/>
    <result property="produceTime" column="produce_time"/>
    <result property="carType" column="car_type"/>
    </resultMap>
    <!--resultMap属性的值必须和resultMap标签中id属性值一致。-->
    <select id="selectAllByResultMap" resultMap="carResultMap">
    select * from t_car
    </select>
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值