MyBatis的resultType和resultMap返回值的用法和区别

resultType

一、返回一般类型数据

比如:根据商品属性id来查询商品的名称

mapper接口:

//根据id获得数据库中的productName 字段的值
String getProductNameById(Integer id);

SQL映射文件:

   <!-- 
        指定 resultType 返回值类型时 String 类型的,
        string 在这里是一个别名,代表的是 java.lang.String 

        对于引用数据类型,都是将大写字母转小写,比如 HashMap 对应的别名是 "hashmap"
        基本数据类型考虑到重复的问题,会在其前面加上 "_",比如 byte 对应的别名是 "_byte"
    -->
    <select id="getProductNameById" resultType="string">
        select productName from tb_product where id = #{id}
    </select>

二、返回实体JavaBean类型

比如:根据实体的某个字段来查找数据库信息,把查询结果封装到某个实体JavaBean类型中

mapper接口:

//根据id查询商品信息,并把信息封装成 Product 对象
Produtc getProductById(Integer id);

SQL映射文件:

    <!-- 
        通过 resultType 指定查询的结果是 Product 类型的数据,resultType = com.lbz.entity.Product(你项目对应的包路径),只需要指定 resultType 的类型,MyBatis 会自动将查
        询的结果映射成 JavaBean 中的属性
    -->
    <select id="getProductById" resultType="com.lbz.entity.Product">
        select * from tb_product where id = #{id}
    </select>

三、返回List类型

比如:有时候我们要查询的数据不止一条,比如:模糊查询,全表查询等,这时候返回的数据可能不止是一条数据,对于多数据的处理可以存放在List集合中

mapper接口:

//根据商品名字来查询商品(模糊查询)
List<Product> selectByProductNameLike(String productName);

SQL映射文件:

  <!-- 模糊查询商品 -->
    <select id="selectByProductNameLike" parameterType="string" resultType="com.lbz.entity.Product">
        select
        <include refid="Base_Column_List"/>
        from tb_product
        where productNamelike #{productName}
    </select>

四、返回Map类型

mapper接口:

//根据 id 查询信息,并把结果信息封装成 Map 
Map<String, Object> getProductAsMapById(Integer id);

SQL映射文件:

    <!-- 
        注意这里的 resultType 返回值类型是 "map"
     -->
    <select id="getProductAsMapById" resultType="map">
        select * from tb_product where id = #{id}
    </select>