mybatis 基础理解resultType和resultMap

resultType和resultMap:

1.resultType:

一、返回一般数据类型
比如要根据 id 属性获得数据库中的某个字段值。

mapper (dao)接口:

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


Mapper.xml 映射文件:

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

对于引用数据类型,都是将大写字母转小写,比如 HashMap 对应的别名是 'hashmap'

基本数据类型考虑到重复的问题,会在其前面加上 '_',比如 byte 对应的别名是 '_byte'-->

<select id="getStuNameById" resultType="string">
      select username from t_student where id = #{id}
</select>

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

mapper (dao)接口:

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

Mapper.xml  映射文件:

  <!-- 通过 resultType 指定查询的结果是 Student类型的数据 只需要指定 resultType 的类型,MyBatis 会自动将查询的结果映射成 JavaBean 中的属性-->

  <select id="getStuById" resultType="student">
      select * from t_student where id = #{id}
  </select>

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

mapper(dao) 接口:

    // 假如是全表查询数据,将查询的数据封装成Student类型的集合
    List<Student> getAllStus();

Mapper.xml  映射文件:

   <!--注意这里的 resultType 返回值类型是集合内存储数据的类型,不是 'list'-->
   <select id="getAllStus" resultType="student">
       select * from t_student
   </select>

四、返回Map类型
MyBatis支持将查询的数据封装成Map。

1. 如果查询的结果是一条,我们可以把查询的数据以{表字段名, 对应的值}方式存入到Map中。

mapper (dao)接口:

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

Mapper.xml  映射文件:

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

2. 如果查询的结果是多条数据,我们也可以把查询的数据以{表中某一字段名, JavaBean}方式来封装成Map。

mapper (dao)接口:

// 查询所有学生的信息,把数据库中的 'id' 字段作为 key,对应的 value 封装成 Student 对象
// @MapKey 中的值表示用数据库中的哪个字段名作 key
@MapKey("id")
Map<Integer, Student> getAllStusAsMap();

Mapper.xml  映射文件:

<!--注意 resultType 返回值类型,不再是 'map',而是 Map 的 value 对应的 JavaBean 类型-->
<select id="getAllStusAsMap" resultType="student">
    select * from t_student
</select>

2.resultmap:(重点)

 1 <!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
 2 <resultMap id="唯一的标识" type="映射的pojo对象">
 3   <id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
 4   <result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
 5 
 6 
 7   <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
 8     <id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
 9     <result  column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
10   </association>
11 
12 
13   <!-- 集合中的property须为oftype定义的pojo对象的属性-->
14   <collection property="pojo的集合属性" ofType="集合中的pojo对象">
15     <id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
16     <result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />  
17   </collection>
18 </resultMap>

UserDao.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.etc.dao.UserDao">
 4     <resultMap id="myuser" type="user">
 5         <id property="id" column="id"></id>
 6         <result property="name" column="name"></result>
 7         <result property="sal" column="sal"></result>
 8         <result property="birth" column="birthday"></result>
 9         <collection property="addresses" ofType="address">
10             <id property="id" column="aid"></id>
11             <result property="name" column="aname"></result>
12         </collection>
13     </resultMap>
14 
15     <insert id="save" useGeneratedKeys="true" keyProperty="id">
16         insert into t_user(name,sal,birthday) values(#{name},#{sal},#{birth})
17     </insert>
18 
19     <update id="update">
20         update t_user set name=#{name},sal=#{sal},birth=#{birth} where id=#{id}
21     </update>
22 
23     <delete id="delete">
24         delete from t_user where id =#{id}
25     </delete>
26 
27     <!--<select id="queryById" resultType="com.etc.entity.User">-->
28     <!--select u.id,u.name,u.sal,u.birthday,a.id aid,a.name aname from t_user u,t_address a where a.user_id=u.id and u.id=#{id}-->
29     <select id="queryById" resultMap="myuser">
30    SELECT
31     u.id,
32     u. NAME,
33     u.sal,
34     u.birthday,
35     a.id aid,
36     a. NAME aname
37 FROM
38     t_user u,
39     t_address a,
40     t_user_address ua
41 WHERE
42     u.id = ua.user_id
43   AND ua.address_id = a.id
44   AND u.id = #{id}
45 </select>
46 
47     <select id="queryAll" resultMap="myuser">
48        SELECT
49     u.id,
50     u. NAME,
51     u.sal,
52     u.birthday,
53     a.id aid,
54     a. NAME aname
55 FROM
56     t_user u,
57     t_address a,
58     t_user_address ua
59 WHERE
60     u.id = ua.user_id
61     AND ua.address_id = a.id
62     </select>
63 </mapper>

UserDao接口:

 1 package com.etc.dao;
 2 
 3 import com.etc.entity.User;
 4 
 5 import java.util.List;
 6 
 7 public interface UserDao {
 8     //@Param 是在 userDAO.xml中使用
 9     // 参数是一个可以不写,多于一个的时候,一定要写
10     //void save(@Param("name") String ne, @Param("sal") double sal, @Param("birth") Date birth);
11     void save(User user);
12 
13     void update(User user);
14 
15     void delete(int id);
16 
17     User queryById(int id);
18 
19     List<User> queryAll();
20 }

 useGeneratedKeys="true" keyProperty="id":

官方的说法是该参数的作用是:“允许JDBC支持自动生成主键,需要驱动兼容”,如何理解这句话的意思?

在使用mybatis时,常常会出现这种需求:
当主键id是自增的情况下,添加一条记录的同时,其主键id是不能使用的,当我们取出主键id的值发现id为null,但是有时我们需要该主键,这时我们该如何处理呢?
这时我们只需要在其对应xxxmapper.xml中加入该属性即可。则允许 JDBC 支持自动生成主键,并可将自动生成的主键返回。

<insert id="save" useGeneratedKeys="true" keyProperty="id">
insert into t_user(name,sal,birthday) values(#{name},#{sal},#{birth})
</insert>


UserDaoTest:
 1 package com.etc.dao;
 2 
 3 import com.etc.entity.User;
 4 import org.apache.ibatis.io.Resources;
 5 import org.apache.ibatis.session.SqlSession;
 6 import org.apache.ibatis.session.SqlSessionFactory;
 7 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
 8 import org.junit.Test;
 9 
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.util.List;
13 
14 public class UserDaoTest {
15 
16     @Test
17     public void testSave() throws IOException {
18         //加载配置文件,   // 会话工厂
19         InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
20         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
21         // 会话 == 相当于数据库连接
22         SqlSession session = sqlSessionFactory.openSession();
23         //调用语句
24         //session.insert("com.etc.dao.UserDAO.save");
25         //session.insert("com.etc.dao.UserDAO.select");
26         UserDao userDAO = session.getMapper(UserDao.class);
27 //        User user = new User();
28 //        user.setName("asdasdaa");
29 //        user.setSal(1000.01);
30 //        user.setBirth(new Date());
31 //        user.setId(15);
32 //        userDAO.save("asdasdaa",1000.01,new Date());
33 //        System.out.println(user.getId());
34 //        userDAO.update(user);
35 //        userDAO.delete(15);
36 //        User user2 = userDAO.queryById(5);
37 //        System.out.println(user2);
38         List<User> list=userDAO.queryAll();
39         for (User u:list){
40             System.out.println(u);
41         }
42         //提交, mybatis自动开启了事务
43         session.commit();
44         //关闭连接
45         session.close();
46     }
47 }

附件:mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration PUBLIC
 3         "-//mybatis.org//DTD Config 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 <configuration>
 6 
 7     <typeAliases>
 8         <typeAlias type="com.etc.entity.User" alias="user"></typeAlias>
 9         <package name="com.etc.entity"></package>
10     </typeAliases>
11 
12     <!-- 配置环境变量 -->
13     <!-- 开发 测试  预生产 生产 -->
14     <environments default="development">
15         <environment id="development">
16             <transactionManager type="JDBC"/>
17             <dataSource type="POOLED">
18                 <property name="driver" value="com.mysql.jdbc.Driver"/>
19                 <property name="url"
20                           value="jdbc:mysql://127.0.0.1:3310/mybatis"/>
21                 <property name="username" value="root"/>
22                 <property name="password" value="123456"/>
23             </dataSource>
24         </environment>
25     </environments>
26 
27 
28     <!-- 配置mappers -->
29     <mappers>
30         <mapper resource="UserDao.xml"></mapper>
31         <mapper resource="AddressDAO.xml"></mapper>
32     </mappers>
33 
34 </configuration>
View Code
原文地址:https://www.cnblogs.com/LiuOOP/p/11232046.html