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:(重点)

 <!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultMap id="唯一的标识" type="映射的pojo对象">
<id column="表的主键字段,或者可以为查询语句中的别名字段" jdbcType="字段类型" property="映射pojo对象的主键属性" />
<result column="表的一个字段(可以为任意表的一个字段)" jdbcType="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/> <association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
<id column="关联pojo对象对应表的主键字段" jdbcType="字段类型" property="关联pojo对象的主席属性"/>
<result column="任意表的字段" jdbcType="字段类型" property="关联pojo对象的属性"/>
</association> <!-- 集合中的property须为oftype定义的pojo对象的属性-->
<collection property="pojo的集合属性" ofType="集合中的pojo对象">
<id column="集合中pojo对象对应的表的主键字段" jdbcType="字段类型" property="集合中pojo对象的主键属性" />
<result column="可以为任意表的字段" jdbcType="字段类型" property="集合中的pojo对象的属性" />
</collection>
</resultMap>

UserDao.xml

 <?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.etc.dao.UserDao">
<resultMap id="myuser" type="user">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="sal" column="sal"></result>
<result property="birth" column="birthday"></result>
<collection property="addresses" ofType="address">
<id property="id" column="aid"></id>
<result property="name" column="aname"></result>
</collection>
</resultMap> <insert id="save" useGeneratedKeys="true" keyProperty="id">
insert into t_user(name,sal,birthday) values(#{name},#{sal},#{birth})
</insert> <update id="update">
update t_user set name=#{name},sal=#{sal},birth=#{birth} where id=#{id}
</update> <delete id="delete">
delete from t_user where id =#{id}
</delete> <!--<select id="queryById" resultType="com.etc.entity.User">-->
<!--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}-->
<select id="queryById" resultMap="myuser">
SELECT
u.id,
u. NAME,
u.sal,
u.birthday,
a.id aid,
a. NAME aname
FROM
t_user u,
t_address a,
t_user_address ua
WHERE
u.id = ua.user_id
AND ua.address_id = a.id
AND u.id = #{id}
</select> <select id="queryAll" resultMap="myuser">
SELECT
u.id,
u. NAME,
u.sal,
u.birthday,
a.id aid,
a. NAME aname
FROM
t_user u,
t_address a,
t_user_address ua
WHERE
u.id = ua.user_id
AND ua.address_id = a.id
</select>
</mapper>

UserDao接口:

 package com.etc.dao;

 import com.etc.entity.User;

 import java.util.List;

 public interface UserDao {
//@Param 是在 userDAO.xml中使用
// 参数是一个可以不写,多于一个的时候,一定要写
//void save(@Param("name") String ne, @Param("sal") double sal, @Param("birth") Date birth);
void save(User user); void update(User user); void delete(int id); User queryById(int id); List<User> queryAll();
}

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:
 package com.etc.dao;

 import com.etc.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test; import java.io.IOException;
import java.io.InputStream;
import java.util.List; public class UserDaoTest { @Test
public void testSave() throws IOException {
//加载配置文件, // 会话工厂
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 会话 == 相当于数据库连接
SqlSession session = sqlSessionFactory.openSession();
//调用语句
//session.insert("com.etc.dao.UserDAO.save");
//session.insert("com.etc.dao.UserDAO.select");
UserDao userDAO = session.getMapper(UserDao.class);
// User user = new User();
// user.setName("asdasdaa");
// user.setSal(1000.01);
// user.setBirth(new Date());
// user.setId(15);
// userDAO.save("asdasdaa",1000.01,new Date());
// System.out.println(user.getId());
// userDAO.update(user);
// userDAO.delete(15);
// User user2 = userDAO.queryById(5);
// System.out.println(user2);
List<User> list=userDAO.queryAll();
for (User u:list){
System.out.println(u);
}
//提交, mybatis自动开启了事务
session.commit();
//关闭连接
session.close();
}
}

附件:mybatis-config.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC
"-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration> <typeAliases>
<typeAlias type="com.etc.entity.User" alias="user"></typeAlias>
<package name="com.etc.entity"></package>
</typeAliases> <!-- 配置环境变量 -->
<!-- 开发 测试 预生产 生产 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://127.0.0.1:3310/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments> <!-- 配置mappers -->
<mappers>
<mapper resource="UserDao.xml"></mapper>
<mapper resource="AddressDAO.xml"></mapper>
</mappers> </configuration>

mybatis 基础理解resultType和resultMap的更多相关文章

  1. Mybatis笔记四:Mybatis中的resultType和resultMap查询操作实例详解

    resultType和resultMap只能有一个成立,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,resultMap解决复杂查询是的映射问题.比 ...

  2. 【mybatis笔记】 resultType与resultMap的区别

    序言: 昨天做一个项目,看到很多刚开始用mybatis的同事对于resultType和resultMap的理解与使用含糊不清,这里我试图用最好理解的说法写一写,欢迎大家勘误. 两者异同: 相同点:re ...

  3. MyBatis中的resultType和resultMap

    MyBatis的查询在进行映射的时候,返回值类型可以使用resultType同时也可以使用resultMap.前者表示直接的返回值类型,一般是domain名称,当然这里可以写domain的全部路径也可 ...

  4. mybatis基础学习2---(resultType和resultMap的用法和区别)和setting的用法

    1:resultType和resultMap两者只能有一个成立 2:resultMap可以解决复杂查询时的映射问题 3:使用 resultType使用 ------------------------ ...

  5. [转]MyBatis中resultType与resultMap区别

    MyBatis中关于resultType和resultMap的具体区别如下: MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap.resu ...

  6. MyBatis标签之Select resultType和resultMap

    摘要:介绍MyBatis 中Select标签的两个属性resultType和resultMap及其区别. 1 MyBatis动态SQL之if 语句 2 MyBatis动态sql之where标签|转 3 ...

  7. Mybatis第七篇【resultMap、resultType、延迟加载】

    resultMap 有的时候,我们看别的映射文件,可能看不到以下这么一段代码: <resultMap id="userListResultMap" type="us ...

  8. Mybatis源码分析--返回值ResultType和ResultMap

    这一篇博客我们来介绍一下Mybatis执行sql语句返回的结果值的到实体对象的映射机制.首先ResultType和ResultMap的使用方式是不同的. ResultType的使用方式: result ...

  9. MyBatis中resultType和resultMap的区别

    resultType和resultMap功能类似  ,都是返回对象信息  ,但是resultMap要更强大一些 ,可自定义.因为resultMap要配置一下,表和类的一一对应关系,所以说就算你的字段名 ...

随机推荐

  1. 初次接触python的re模块

    刷CF的时候,看到一个简单的题目,可以用来练练正则表达式 于是乎找到了re.sub的用法,说明如下 re.sub: (pattern, repl, string, count=0, │       f ...

  2. JRE System Library、Referenced Libraries、Web App Libraries的含义

    JRE System Library.Referenced Libraries.Web App Libraries 这三个都是jar包的存放集合. JRE System Library:指Java S ...

  3. php实现图片以base64显示的方法达到效果

    目前Data URI scheme支持的类型有: data:text/plain,文本数据data:text/html,HTML代码data:text/html;base64,base64编码的HTM ...

  4. 启动Jmeter录制代理进行录制,报 jmeter.protocol.http.proxy.ProxyControl

    使用jmeter代理录制Http请求时,启动HTTP(S) Test Script Recorder报jmeter.protocol.http.proxy.ProxyControl, 日志为: 201 ...

  5. pl/sql基础知识—pl/sql块介绍

    n  介绍 块(block)是pl/sql的基本成型单元,编写pl/sql程序实际上就是编写pl/sql块.要完成相对简单的应用功能,可能只需要编写一个pl/sql块:但是如果要想实现复杂的功能,可能 ...

  6. 洛谷 P1505 [国家集训队]旅游 树链剖分

    目录 题面 题目链接 题目描述 输入输出格式 输入格式 输出格式 输入输出样例 输入样例: 输出样例: 说明 思路 AC代码 总结 题面 题目链接 P1505 [国家集训队]旅游 题目描述 Ray 乐 ...

  7. 每天一个linux命令(2): nl命令

    0.学习时间 2014-05-16 1.命令格式 nl [参数] 文件名 (文件名也缺省的情况下, 从标准输入中读入) 2.命令参数 -b t 空行不加行号(默认) -b a  空行也加行号(类似于c ...

  8. kendo grid 使用小结

    需要注意的: 1. id,如果没有指定id则会导致create.update等操作无法正常使用. 头疼事项: 1. 服务端失败返回error数据.如果是编辑状态,还不能友好提示错误.当然可以使用大量代 ...

  9. Notepad++ ssh NppFTP链接linux

    Notepad++是一套非常有特色的自由软件的纯文字编辑器,有完整的中文化接口及支持多国语言编写的功能.现在用Notepad++来远程编辑Linux系统文本文件. Notepad++ 1.Linux操 ...

  10. 百度网盘直链下载助手(MacOS&Chrome)

    简介 众所周知,通过百度网盘(未开通会员)直接下载文件的速度极慢,通过安装浏览器插件可以极大的提高下载速度. 安装文件 Tampermonkey NeatDownloadManager Extensi ...