MyBatis学习(五)resultMap测试
resultMap是MyBatis最强大的元素,它的作用是告诉MyBatis将从结果集中取出的数据转换成开发者所需要得对象。
接下来我们对resultMap进行一个简单测试。(当所需要返回的对象是一个对象关联到另一个对象的结果时)
1.创建一个项目,导入所需的jar包,在src目录下加入两个属性文件db.properyies和log4j.properties。


2.创建两个表,编写两个实体类分别映射这两张表。
-- Table structure for `t_student`
-- ----------------------------
DROP TABLE IF EXISTS `t_student`;
CREATE TABLE `t_student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(18) NOT NULL,
`sex` varchar(3) NOT NULL,
`age` int(11) NOT NULL,
`cid` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `cid` (`cid`),
CONSTRAINT `cid` FOREIGN KEY (`cid`) REFERENCES `t_clazz` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_student
-- ----------------------------
INSERT INTO `t_student` VALUES ('', '张三', '男', '', '');
INSERT INTO `t_student` VALUES ('', '李四', '男', '', '');
INSERT INTO `t_student` VALUES ('', '小红', '女', '', '');
-- ----------------------------
-- Table structure for `t_clazz`
-- ----------------------------
DROP TABLE IF EXISTS `t_clazz`;
CREATE TABLE `t_clazz` (
`id` int(11) NOT NULL,
`code` varchar(18) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ----------------------------
-- Records of t_clazz
-- ----------------------------
INSERT INTO `t_clazz` VALUES ('', '一班');
INSERT INTO `t_clazz` VALUES ('', '二班');
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
//关联的clazz对象
private Clazz clazz;
//省略get、set、toString方法
public class Clazz {
private Integer id;
private String code;
//省略get、set、toString方法
3.编写mybatis-config.xml和SQL映射文件
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>
<!-- 引入 外部db.properties文件-->
<properties resource="db.properties"/>
<!-- 指定 MyBatis 所用日志的具体实现-->
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<!-- 环境配置 -->
<environments default="mysql">
<environment id="mysql">
<!-- 指定事务类型 -->
<transactionManager type="JDBC"/>
<!-- dataSource指数据源配置,POOLED是JDBC连接对象的数据源连接池的实现。 -->
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!-- SQL映射文件位置 -->
<mappers>
<mapper resource="com/dj/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
StudetMapper.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"> <!-- namespace指用户自定义的命名空间 -->
<mapper namespace="com.dj.mapper.StudentMapper">
<!-- 映射学生对象的resultMap -->
<resultMap type="com.dj.domain.Student" id="studentResultMap">
<id property="id" column="id"/>
<id property="name" column="name"/>
<id property="sex" column="sex"/>
<id property="age" column="age"/>
<!-- 关联映射
property:表示返回类型student的属性名 clazz
column:表示数据库的列名
javaType:表示property属性对应的类型名称
select:表示执行一条查询语句,将查询到的结果封装到property所代表的类型对象中。
-->
<association property="clazz" column="cid"
javaType="com.dj.domain.Clazz" select="selectClazzById"/>
</resultMap>
<select id="selectClazzById" resultType="com.dj.domain.Clazz">
select * from t_clazz where id=#{id}
</select>
<select id="selectStudent" resultMap="studentResultMap">
select * from t_student
</select>
</mapper>
4.进行测试,在控制台输出从数据库查询到的学生信息
StudentTest.java
package com.dj.test; import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List; 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 com.dj.domain.Student; public class StudentTest { public static void main(String[] args) throws IOException {
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
List<Student> list = sqlSession.selectList("com.dj.mapper.StudentMapper.selectStudent");
for (Student student : list) {
System.out.println(student);
}
sqlSession.commit();
sqlSession.close();
}
}
运行后可以在控制台看到如下结果:

源码下载路径:https://files.cnblogs.com/files/dj-blog/resultMapest.zip
MyBatis学习(五)resultMap测试的更多相关文章
- mybatis学习 (五) POJO的映射文件
Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心. 1.parameterType(输入类型) 通过parameterType ...
- Mybatis学习笔记-ResultMap结果集映射
解决属性名与字段名不一致的问题 新建项目 --> 测试实体类字段不一致的情况 数据库字段:id,name,pwd 实体类属性:id,name,password 输出结果 User{id=1, n ...
- mybatis学习 十三 resultMap标签 一对一
1 .<resultMap>标签 写在mapper.xml中,由程序员控制SQL查询结果与实体类的映射关系. 在写<select>标签中,有一个resultType属性,此时s ...
- mybatis学习五 log4j
1. log4j(log for java)由 apache 推出的开源免费日志处理的类库.2. 为什么需要日志: 2.1 在项目中编写 System.out.println();输出到控制台,当项 ...
- mybatis 学习五 二级缓存不推荐使用
mybatis 二级缓存不推荐使用 一 mybatis的缓存使用. 大体就是首先根据你的sqlid,参数的信息自己算出一个key值,然后你查询的时候,会先把这个key值去缓存中找看有没有value,如 ...
- mybatis 学习五 动态SQL语句
3.1 selectKey 标签 在insert语句中,在Oracle经常使用序列.在MySQL中使用函数来自动生成插入表的主键,而且需要方法能返回这个生成主键.使用myBatis的selectKey ...
- Mybatis学习笔记导航
Mybatis小白快速入门 简介 本人是一个Java学习者,最近才开始在博客园上分享自己的学习经验,同时帮助那些想要学习的uu们,相关学习视频在小破站的狂神说,狂神真的是我学习到现在觉得最GAN的老师 ...
- MyBatis学习 之 二、SQL语句映射文件(1)resultMap
目录(?)[-] 二SQL语句映射文件1resultMap resultMap idresult constructor association联合 使用select实现联合 使用resultMap实 ...
- mybatis学习笔记(五):mybatis 逆向工程
mybatis学习笔记(五):mybatis 逆向工程 在日常开发中,如果数据库中存在多张表,自己手动创建 多个pojo 类和编写 SQL 语法配置文件,未免太过繁琐,mybatis 也提供了一键式生 ...
- (转)MyBatis框架的学习(五)——一对一关联映射和一对多关联映射
http://blog.csdn.net/yerenyuan_pku/article/details/71894172 在实际开发中我们不可能只是对单表进行操作,必然要操作多表,本文就来讲解多表操作中 ...
随机推荐
- Swiper.js
Swiper常用于移动端网站的内容触摸滑动 http://idangero.us/swiper/#.WUCSo_mGOUk
- linux 简易启动脚本
#/bin/bash pid=`ps -ef | grep 'testDemo' | grep -v grep |awk '{print $2}'` in start) nohup java -j t ...
- 【整合】input标签JS改变Value事件处理方法
某人需要在时间控件给文本框赋值时,触发事件函数.实现的效果: 1.文本框支持手工输入,通过用户输入修改值,手工输入结束后触发事件.阻塞在于失去焦点后才触发(输入过程中不触发事件) 2.通过JS方法修改 ...
- php sql uuid 32位
最近表中id需要用到此值来作为唯一主键 其含义是通用唯一识别码.具体好处及应用可百度百科,链接给你https://baike.baidu.com/item/UUID/5921266?fr=aladdi ...
- MySQL之数据的备份与还原
备份db_book:这里用到了cmd,以管理员方式运行,不然后面使用mysqldump会被拒绝访问!!! 1.启动cmd,输入命令,切换到MySQL的bin文件: 2.然后输入备份命令: 备份好的sq ...
- python链接MySQLdb报错:2003
使用python链接Mysql数据库操作,遇到问题! 问题如图所示: 解决方法:将"localhost"改为"127.0.0.1" db=MySQLdb.con ...
- [2012-05-31]awk记录分割符RS
$awk -v RS= '{print $1}' test RS 默认值为\n 换行符. 此处设置RS= 等效于 RS="" 代表一个空行 (若理解有误请指正,在以下例子中符合) ...
- markdown常用语法教程
1. 标题 总共六级标题,"#"号后面最好加空格,美观可以在后面加上对应数量的"#" # 一级标题 ## 二级标题 ### 三级标题 #### 四级标题 ### ...
- Visual Studio2017数据库数据比较
一.前言 上一篇文章我们介绍了如何使用VS2017对SSMS数据库进行架构比较.这一篇文章我们将继续介绍如何对SSMS数据库的数据进行比较.数据的比较也是很常见的,比如我们要比较当前版本的数据库相对上 ...
- new和newInstance区别
详见:http://blog.yemou.net/article/query/info/tytfjhfascvhzxcytp55 在初始化一个类,生成一个实例的时候:newInstance() ...