mybatis中的 resultType和resultMap的使用

两个都是输出结果类型的。

1、resultType

        resultType可以输出简单类型

     <!-- 查询数据的条数 -->
    <select id="queryUserCount" resultType="int">
        SELECT count(*) FROM  user
    </select>
        输出pojo对象
 
     <select id="queryUser"  resultType="com.star.entity.User">
         SELECT * FROM `user` WHERE id=#{id}
     </select>

        注意:用resultType的时候,要保证数据库的列名与java实体类的属性名相同,要不然输出的结果代码中接收的为null。这个问题我遇见了几次。

2、resultMap

        

<resultMap  id="baseResultType" type="com.star.entity.user">
        <!-- property:主键在实体类中的属性名 -->
        <!-- column:主键在数据库中的列名 -->
       
        <id property="id" column="user_id" />

        <!-- 定义普通属性 -->
        <result property="name" column="user_name" />
        <result property="number" column="user_number" />
    </resultMap>

    <!-- 查询所有的用户 -->
    <select id="queryUserAll" resultMap="baseResultType">
        SELECT * FROM user
    </select>

        注意:resultMap适合使用返回值是自定义实体类的情况,是将字段名和属性名做一个对应关系;sql查询数据库字段名和实体类中的属性名不一致,则需要定义它们的映射关系。

        通常数据库字段是和实体类中的字段是有一定出入的,此时使用较多的为resultMap来做映射关系。

猜你喜欢

转载自blog.csdn.net/m0_71867302/article/details/132826218