输入映射和输出映射
Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。
环境准备
复制 【Mybatis入门(1)】的工程即可
parameterType(输入类型)
传递简单类型
参考【Mybatis入门(1)】内容。
使用#{}占位符,或者${}进行sql拼接。
传递pojo对象
参考【Mybatis入门(1)的内容。
Mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称。
传递pojo包装对象
- 开发中通过可以使用pojo传递查询条件。
-
查询条件可能是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如查询用户信息的时候,将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。
包装对象:Pojo类中的一个属性是另外一个pojo。 - 需求:根据用户名模糊查询用户信息,查询条件放到QueryVo的user属性中。
编写QueryVo
package com.mybatis.pojo;
import java.io.Serializable;
public class queryVo implements Serializable {
private static final long seriaLVersionUID = 1L;
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Sql语句
SELECT * FROM user WHERE username LIKE '%wu%'
Mapper.xml文件
在user.xml中配置sql,如下图。
<!-- 使用queryvo查询-->
<select id="findUserByqueyVo" parameterType="queryVo" resultType="com.mybatis.pojo.User">
select * from user where username like "%"#{user.username}"%"
</select>
Mapper接口
在UserMapperDao接口中添加方法,如下图:
public List<User> findUserByqueyVo(queryVo vo);
测试方法
@Test
public void testMapper2() throws IOException {
// 加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
// 创建sqlsessionfactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(in);
// 创建sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
// sqlsession帮我实现一个实现类(给接口)
UserMapperDao userMapperDao = sqlSession.getMapper(UserMapperDao.class);
queryVo vo = new queryVo();
User user = new User();
user.setUsername("wu");
vo.setUser(user);
List<User> us = userMapperDao.findUserByqueyVo(vo);
System.out.println(us.toString());
}
resultType(输出类型)
输出简单类型
需求:查询用户表数据条数
sql:SELECT count(*) FROM user
Mapper.xml文件
在User.xml中配置sql,如下图:
<select id="findCount" resultType="Integer">
SELECT count(*) from user
</select>
Mapper接口
//查询用户表条数
public Integer findCount();
测试方法
@Test
public void testMapper3() throws IOException {
// 加载核心配置文件
String resource = "sqlMapConfig.xml";
InputStream in = Resources.getResourceAsStream(resource);
// 创建sqlsessionfactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(in);
// 创建sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
// sqlsession帮我实现一个实现类(给接口)
UserMapperDao userMapperDao = sqlSession.getMapper(UserMapperDao.class);
Integer count= userMapperDao.findCount();
System.out.println(count);
}
输出pojo对象
参考【Mybatis入门(1)】内容。
输出pojo列表
参考【Mybatis入门(1)】内容。
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
声明pojo对象
Order对象:
public class Order {
// 订单id
private int id;
// 用户id
private Integer userId;
// 订单号
private String number;
// 订单创建时间
private Date createtime;
// 备注
private String note;
get/set。。。
}
Mapper.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.mybatis.mapper.OrderMapperDao">
<!-- 查询所有的订单数据 -->
<select id="queryOrderAll" resultType="order">
SELECT id, user_id,
number,
createtime, note FROM `order`
</select>
</mapper>
Mapper接口
编写接口如下:
public interface OrderMapperDao {
/**
* 查询所有订单
*
* @return
*/
List<Order> queryOrderAll();
}
测试方法
编写测试方法OrderMapperTest如下:
public class OrderMapperTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws Exception {
InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testQueryAll() {
// 获取sqlSession
SqlSession sqlSession = this.sqlSessionFactory.openSession();
// 获取OrderMapper
OrderMapper orderMapper = sqlSession.getMapper(OrderMapper.class);
// 执行查询
List<Order> list = orderMapper.queryOrderAll();
for (Order order : list) {
System.out.println(order);
}
}
}
测试效果如下图:
发现userId为null
解决方案:使用resultMap
使用resultMap
由于上边的mapper.xml中sql查询列(user_id)和Order类属性(userId)不一致,所以查询结果不能映射到pojo中。
需要定义resultMap,把orderResultMap将sql查询列(user_id)和Order类属性(userId)对应起来
改造order.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.mybatis.mapper.OrderMapperDao">
<!-- 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>
效果
只需要修改Mapper.xml就可以了,再次测试结果如下:
动态sql
通过mybatis提供的各种标签方法实现动态拼接sql。
需求:根据性别和名字查询用户
查询sql:
SELECT id, username, birthday, sex, address FROM user
WHERE sex = 1 AND username LIKE '%wu%'
If标签
Mapper.xml文件
user.xml配置sql,如下:
<!-- 根据条件查询用户 -->
<select id="queryUserByWhere" parameterType="user" resultType="user">
SELECT id, username, birthday, sex, address FROM `user`
WHERE sex = #{sex} AND username LIKE
'%${username}%'
</select>
Mapper接口
测试方法
@Test
public void testQueryUserByWhere() {
// mybatis和spring整合,整合之后,交给spring管理
SqlSession sqlSession = this.sqlSessionFactory.openSession();
// 创建Mapper接口的动态代理对象,整合之后,交给spring管理
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 使用userMapper执行根据条件查询用户
User user = new User();
user.setSex("1");
user.setUsername("张");
List<User> list = userMapper.queryUserByWhere(user);
for (User u : list) {
System.out.println(u);
}
// mybatis和spring整合,整合之后,交给spring管理
sqlSession.close();
}
效果
测试效果如下图:
如果注释掉 user.setSex("1"),测试结果如下图:
测试结果二很显然不合理。
按照之前所学的,要解决这个问题,需要编写多个sql,查询条件越多,需要编写的sql就更多了,显然这样是不靠谱的。
解决方案,使用动态sql的if标签
使用if标签
改造Mapper.xml,如下
<!-- 根据条件查询用户 -->
<select id="queryUserByWhere" parameterType="user" resultType="user">
SELECT id, username, birthday, sex, address FROM `user`
WHERE 1=1
<if test="sex != null and sex != ''">
AND sex = #{sex}
</if>
<if test="username != null and username != ''">
AND username LIKE
'%${username}%'
</if>
</select>
注意字符串类型的数据需要要做不等于空字符串校验。