【SSM】MyBatis(九.查询语句专题)

文章目录

  • 1.返回Car
  • 2.返回List< Car >
  • 3.返回map集合
  • 4.返回List< Map >
  • 5. 返回Map
  • 6.结果映射
    • 6.1 使用resultMap
    • 6.2 开启驼峰命名
  • 7.返回总记录条数

1.返回Car

CarMapper.xml

    <select id="selectById" resultType="Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
        where
            id = #{id}
    select>

2.返回List< Car >

CarMapper.xml

    <select id="selectAll" resultType="Car">
        select
            id,
            car_num as carNum,
            brand,
            guide_price as guidePrice,
            produce_time as produceTime,
            car_type as carType
        from
            t_car
    select>

3.返回map集合

CarMapper.xml

    <select id="selectByIdRetMap" resultType="map">
        select * from t_car where id = #{id}
    select>

4.返回List< Map >

CarMapper.xml

    <select id="selectAllRetListMap" resultType="map">
        select * from t_car
    select>

CarMapper.java

List<Map<String, Object>> selectAllRetListMap();

5. 返回Map

CarMapper.xml

    <select id="selectAllRetMap" resultType="map">
        select * from t_car
    select>

CarMapper.java


  /**
   * 返回大Map集合,
   * 大Map集合的key为每一条记录的主键值,
   *           value为每一条记录
   * @return
   */
  @MapKey("id") //将结果的id 作为大Map集合的key
  Map<Long, Map<String, Object>> selectAllRetMap();

6.结果映射

查询结果的列名和java对象的属性名对应不上怎么办?
● 第一种方式:as 给列起别名
● 第二种方式:使用resultMap进行结果映射
● 第三种方式:是否开启驼峰命名自动映射(配置settings)

6.1 使用resultMap

CarMapper.xml

    
    <resultMap id="carResultMap" type="Car">
        
        <id property="id" column="id"/>
        <result property="carNum" column="car_num"/>
        
        
        <result property="brand" column="brand" javaType="string" jdbcType="VARCHAR"/>
        <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>

CarMapper.java

    List<Car> selectAllByResultMap();

6.2 开启驼峰命名

在mybatis-config.xml文件中进行配置:


<settings>
  <setting name="mapUnderscoreToCamelCase" value="true"/>
settings>

7.返回总记录条数

CarMapper.xml

<select id="selectTotal" resultType="long">
  select count(*) from t_car
select>

你可能感兴趣的:(SSM,mybatis,java,mysql)