Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)
一、parameterType(输入类型)
1.1 传递简单类型
<!-- 根据用户id查询用户 -->
<select id="queryUserById" parameterType="int"
resultType="cn.itcast.mybatis.pojo.User">
SELECT * FROM `user` WHERE id = #{id}
</select> <!-- 根据用户名模糊查询用户 -->
<select id="queryUserByUsername" parameterType="string"
resultType="cn.itcast.mybatis.pojo.User">
SELECT * FROM `user` WHERE username LIKE '%${value}%'
</select>
使用#{}占位符,或者${}进行sql拼接
1.2 传递pojo对象
<!-- 保存用户 -->
<insert id="saveUser" parameterType="cn.itcast.mybatis.pojo.User">
INSERT INTO `user`(username,birthday,sex,address) VALUES
(#{username},#{birthday},#{sex},#{address});
</insert>
Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。
1.3 传递pojo包装对象
包装对象:Pojo类中的一个属性是另外一个pojo。
需求:根据用户名模糊查询用户信息,查询条件放到QueryVo的user属性中。
1.3.1 编写QueryVo
public class QueryVo {
    // 包含其他的pojo
    private User user;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
}
1.3.2 Mapper.xml文件
在UserMapper.xml中配置sql:
<!-- 使用包装类型查询用户 -->
<select id="queryUserByQueryVo" parameterType="queryVo" resultType="user">
SELECT * FROM `user` WHERE username LIKE '%${user.username}%'
</select>
1.3.3 Mapper接口
在UserMapper接口中添加方法:
/**
* 根据包装类型查询用户
* @param queryVo
* @return
*/
List<User> queryUserByQueryVo(QueryVo queryVo);
1.3.4 测试方法
@Test
public void testQueryUserByQueryVo() throws Exception {
// mybatis和spring整合,整合之后,交给spring管理
SqlSession sqlSession = sqlSessionFactory.openSession();
// 创建Mapper接口的动态代理对象,整合之后,交给spring管理
UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 使用userMapper执行查询,使用包装对象
QueryVo queryVo = new QueryVo();
// 设置user条件
User user = new User();
user.setUsername("张");
// 设置到包装对象中
queryVo.setUser(user); // 执行查询
List<User> list = userMapper.queryUserByQueryVo(queryVo);
for (User user2 : list) {
System.out.println(user2);
} // mybatis和spring整合,整合之后,交给spring管理
sqlSession.close();
}
二、resultType(输出类型)
2.1 输出简单类型
需求:查询用户表数据条数
sql:SELECT count(*) FROM `user`
2.1.1 Mapper.xml文件
在UserMapper.xml中配置sql:
<!-- 查询用户数据条数 -->
<select id="queryUserCount" resultType="int">
SELECT COUNT(*) FROM `user`
</select>
2.1.2 Mapper接口
在UserMapper添加方法:
/**
* 查询用户数据条数
* @return
*/
int queryUserCount();
2.1.3 测试方法
@Test
public void testQueryUserCount() throws Exception {
// mybatis和spring整合,整合之后,交给spring管理
SqlSession sqlSession = sqlSessionFactory.openSession();
// 创建Mapper接口的动态代理对象,整合之后,交给spring管理
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 使用userMapper执行查询用户数据条数
int count = userMapper.queryUserCount();
System.out.println(count); // mybatis和spring整合,整合之后,交给spring管理
sqlSession.close();
}
2.2 输出pojo对象
<select id="queryUserById" parameterType="int"
resultType="cn.itcast.mybatis.pojo.User">
SELECT * FROM `user` WHERE id = #{id}
</select>
2.3 输出pojo列表
<!-- 根据用户名模糊查询用户 -->
<select id="queryUserByUsername" parameterType="string"
resultType="cn.itcast.mybatis.pojo.User">
SELECT * FROM `user` WHERE username LIKE '%${value}%'
</select>
三、resultMap
resultType可以指定将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。
如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。
resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。
需求:查询订单表order的所有数据
sql:SELECT id, user_id, number, createtime, note FROM `order`
3.1 声明pojo对象
数据库表如下图:
  
Order对象:
public class Order {
    // 订单id
    private int id;
    // 用户id
    private Integer userId;
    // 订单号
    private String number;
    // 订单创建时间
    private Date createtime;
    // 备注
    private String note;
   get/set。。。
}
3.2 Mapper.xml文件
创建OrderMapper.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:命名空间,用于隔离sql,还有一个很重要的作用,Mapper动态代理开发的时候使用,需要指定Mapper的类路径 -->
<mapper namespace="cn.itcast.mybatis.mapper.OrderMapper">
<!-- 查询所有的订单数据 -->
<select id="queryOrderAll" resultType="order">
SELECT id,user_id,number,createtime,note FROM `order`
</select>
</mapper>
3.3 Mapper接口
public interface OrderMapper {
    /**
     * 查询所有订单
     * @return
     */
    List<Order> queryOrderAll();
}
3.4 测试方法
public class OrderMapperTest {
    private SqlSessionFactory sqlSessionFactory;
    @Before
    public void init() throws Exception{
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
    }
    @Test
    public void testQueryOrderAll() throws Exception {
        // 获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 获取OrderMapper
        OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
        // 执行查询
        List<Order> list = orderMapper.queryOrderAll();
        for (Order order : list) {
            System.out.println(order);
        }
        sqlSession.close();
    }
}
3.5 测试效果
  
发现userId为null
解决方案:使用resultMap
3.6 使用resultMap
由于上边的mapper.xml中sql查询列(user_id)和Order类属性(userId)不一致,所以查询结果不能映射到pojo中。
需要定义resultMap,把orderResultMap将sql查询列(user_id)和Order类属性(userId)对应起来。
改造OrderMapper.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:命名空间,用于隔离sql,还有一个很重要的作用,Mapper动态代理开发的时候使用,需要指定Mapper的类路径 -->
<mapper namespace="cn.itcast.mybatis.mapper.OrderMapper">
<!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
<!-- id:设置ResultMap的id -->
<resultMap type="order" id="orderResultMap">
<!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
<!-- property:主键在pojo中的属性名 -->
<!-- column:主键在数据库中的列名 -->
<id property="id" column="id" /> <!-- 定义普通属性 -->
<result property="userId" column="user_id" />
<result property="number" column="number" />
<result property="createtime" column="createtime" />
<result property="note" column="note" />
</resultMap> <!-- 查询所有的订单数据 -->
<select id="queryOrderAll" resultMap="orderResultMap">
SELECT
id,user_id,number,createtime,note FROM `order`
</select>
</mapper>
3.7 测试效果
  
Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)的更多相关文章
- MyBatis学习笔记3--使用XML配置SQL映射器
		
<resultMap type="Student" id="StudentResult"> <id property="id&quo ...
 - MyBatis学习笔记(五)——实现关联表查询
		
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4264440.html 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) 1.2.创 ...
 - Mybatis学习笔记(四) —— SqlMapConfig.xml配置文件
		
一.properties(属性) SqlMapConfig.xml可以引用java属性文件中的配置信息 在config下定义db.properties文件,如下所示: db.properties配置文 ...
 - mybatis学习笔记(四)-- 为实体类定义别名两种方法(基于xml映射)
		
下面示例在mybatis学习笔记(二)-- 使用mybatisUtil工具类体验基于xml和注解实现 Demo的基础上进行优化 以新增一个用户为例子,原UserMapper.xml配置如下: < ...
 - Mybatis学习笔记之二(动态mapper开发和spring-mybatis整合)
		
一.输入映射和输出映射 1.1 parameterType(输入类型) [传递简单类型] 详情参考Mybatis学习笔记之一(环境搭建和入门案例介绍) 使用#{}占位符,或者${}进行sql拼接. [ ...
 - mybatis学习笔记(五):mybatis 逆向工程
		
mybatis学习笔记(五):mybatis 逆向工程 在日常开发中,如果数据库中存在多张表,自己手动创建 多个pojo 类和编写 SQL 语法配置文件,未免太过繁琐,mybatis 也提供了一键式生 ...
 - mybatis 学习笔记(三):mapper 代理开发 dao 层
		
mybatis 学习笔记(三):mapper 代理开发 dao 层 优势 通过使用mapper 代理,我们可以不需要去编写具体的实现类(使用 getMapper() 方法自动生成),只需编写接口即可, ...
 - mybatis学习笔记(7)-输出映射
		
mybatis学习笔记(7)-输出映射 标签: mybatis mybatis学习笔记7-输出映射 resultType 输出简单类型 输出pojo对象和pojo列表 resultMap result ...
 - mybatis学习笔记(五) -- maven+spring+mybatis从零开始搭建整合详细过程(附demo和搭建过程遇到的问题解决方法)
		
文章介绍结构一览 一.使用maven创建web项目 1.新建maven项目 2.修改jre版本 3.修改Project Facts,生成WebContent文件夾 4.将WebContent下的两个文 ...
 
随机推荐
- 部署和调优  1.1 nfs部署和优化-2
			
更改共享目录文件默认的所有者和所属组 已知道客户端有个user11用户 cat /etc/passwd user11:x:501:501::/home/user11:/bin/bash 服务端打开 v ...
 - DAY9-python并发之多进程
			
一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程.P ...
 - Linux reboot后数据库无法自动启动
			
需将以下由N改为Y orcl:/data/oracle_db/product/13.2.0/db_1:Y Last login: Thu Aug 27 16:36:19 2015 from 10.10 ...
 - ActiveMQ (一) 介绍与安装
			
ActiveMQ是消息中间件的一种 ActiveMQ 是Apache出品,最流行的,能力强劲的开源消息总线.ActiveMQ 是一个完全支持JMS1.1和J2EE 1.4规范的 JMS Provide ...
 - 指定jdk编译或运行
			
set JAVA_HOME=D:\java\jdk8 set CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOMe%\lib\tools.jar; set Pat ...
 - C++——virtual
			
一.放在父类的函数名前面:多态 1.作用:实现多态:子类可以自定义父类中的virtual函数 #include <iostream> using namespace std; class ...
 - 使用Javascript Ajax 通信操作JSON数据 [上]
			
以前只是知道json的格式而已,也做过的是从数据库获得数据然后弄成json的格式然后赋给HighCharts生成曲线,先把数据库的数据使用array()函数转换成数组,然后使用json_encode( ...
 - ubuntu16安装pylearn2 出现错误提示importerror:no module named six.moves
			
由于市面上的一些教程时间比较早,入门学习时跟随教程安装容易出现各种错误,这些错误基本都是版本不同导致的 所以,我们安装过程中一定要指出包的版本,如果你已经遇到no module named six.m ...
 - noi.ac day5t1 count
			
传送门 分析 首先一个很重要的性质是每个数至少出现一次 所以只有一个数会出现两次 我们只需要求出n+1个数选k个数的方案数再减去重复的部分即可 重复部分于两个相同数中间的距离有关,详见代码 代码 #i ...
 - RPM验证与数字签名(Verify/Signature)
			
RPM验证与数字签名(Verify/Signature) 摘自:https://blog.csdn.net/rhel_admin/article/details/32382391 2014年06月19 ...