Mybatis---resultType与resultMap

首先
resultType与resultMap不能同时用

resultType

只有数据库表中的数据类型与实体类想对应才可以用

用法
**

返回一个list

**
当你返回一个实体类的list,resultType也是写他的包名加类名

例如

public interface HotelMapper {
    // 返回值为List
    public List<Hotel> getHotel(Integer i);
}
public interface HotelMapper {
    // 返回值为List
    public List<Hotel> getHotel(Integer i);
}

返回一个map

package com.pjf.mybatis.dao;

import java.util.Map;
import com.pjf.mybatis.po.Hotel;

public interface HotelMapper {
    // 返回值为Map,key为属性名,value为属性值
    public Map<String, Object> getHotel(Integer i);
}
<?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.pjf.mybatis.dao.HotelMapper">
    <!-- 返回值为map,resultType为map -->
    <select id="getHotel" resultType="map">
        select * from hotel
        where
        id=#{id}
    </select>
</mapper>

resultMap

解决字段名(数据库中的列名)和属性名(java里pojo类中的属性)不一致而导致错误冲突。

例子

<mapper namespace="com.example.dao.SysCityDao">
<!-- 定义ResultMap
     id:唯一标识符,连接select查询标签内的resultmap。
     type:所对应的实体pojo类型 -->
    <resultMap id="cityResultMap" type="com.example.data.SysCity">
    <!-- id标签:主键标签。
     column:查询出的列名(给数据库中的列名定义的别名) 
     property:对应type所指定的java实体类POJO中的属性名-->
        <id column="code" property="cityCode"/>
        <!-- 对普通列的映射定义 -->
        <result column="name" property="cityName"/>
        <result column="type" property="cityType"/>
        <result column="pcode" property="parentCode"/>
        <result column="rmk" property="remark"/>
    </resultMap>

<!-- 使用resultMap进行输出映射 
    resultMap:指定上面定义的resultMap的id(cityResultMap),如果这个resultMap在其它的mapper文件,前面需要加namespace-->
<select id="selectAllCity"  resultMap="cityResultMap">
    <![CDATA[
    select city_code code,city_name name,city_type type,parent_code pcode,remark rmk from sys_city
    ]]>
        <where>
        <if test="code != null and code != ''">
        city_code = #{code}
        </if>
        <if test="name != null  and name != ''">
        AND city_name = #{name}
        </if>
        <if test="type != null  and type != ''">
        AND city_type = #{type}
        </if>
        </where>
    </select>
//城市信息的Dao接口
public interface SysCityDao extends BaseMapper<SysCity> {
    //查看城市基本信息
    public List<SysCity> selectAllCity() throws Exception;
}

参考
mybatis学习(七)——resultType解析
MyBatis-resultType 与 resultMap 中的几种返回类型
MyBatis查询结果resultType返回值类型详细介绍
Mybatis之输出映射resultType与resultMap比较

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RDSunday

爱,就供养;喜欢/受益,就打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值