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的列不会查出来
    Mybatis查询_第1张图片

  4. 用Map来接受对象

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

    Mybatis查询_第2张图片

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

    mybatis:
      configuration:
        map-underscore-to-camel-case: true #开启驼峰映射
    
    /**
    * 查询所有Car,使用resultMap进行结果映射
    * @return
    */
    List<Car> selectAllByResultMap();
    
    
    <resultMap id="carResultMap" type="car">
    <id property="id" column="id"/>
    <result property="carNum" column="car_num"/>
    
    
    <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>
    
    <select id="selectAllByResultMap" resultMap="carResultMap">
    select * from t_car
    select>
    

你可能感兴趣的:(mybatis)