比如要根据 id 属性获得数据库中的某个字段值。

mapper 接口:

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

SQL 映射文件:

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

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

二、返回 JavaBean 类型

比如根据某个字段获得数据库中的信息,把查询的结果信息封装成某个 JavaBean 类型的数据。

mapper 接口:

// 根据 id 查询信息,并把信息封装成 Employee 对象
    Employee getEmpById(Integer id);

 SQL 映射文件:

 <!-- 
        通过 resultType 指定查询的结果是 Employee 类型的数据  
        只需要指定 resultType 的类型,MyBatis 会自动将查询的结果映射成 JavaBean 中的属性
    -->
    <select id="getEmpById" resultType="employee">
        select * from t_employee where id = #{id}
    </select>

三、返回List类型

  //mapper:
  // 假如是全表查询数据,将查询的数据封装成 Employee 类型的集合
    List<Employee> getAllEmps();
  //SQL:
   <!--
        注意这里的 resultType 返回值类型是集合内存储数据的类型,不是 'list'
    -->
    <select id="getAllEmps" resultType="employee">
        select * from t_employee
    </select>

 返回Map类型:

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

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

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐