MyBatis 之 映射文件---动态sql
通过Mybatis提供的各种动态标签实现动态拼接sql,使得mapper映射文件在编写SQL时更加灵活,方便。常用动态SQL标签有:if、where、foreach;
一、if和where
f标签:作为判断入参来使用的,如果符合条件,则把if标签体内的SQL拼接上。
注意:用if进行判断是否为空时,不仅要判断null,也要判断空字符串‘’;
Where标签:会去掉条件中的第一个and符号。
1.PO类和POJO
public class User {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public int getId() {
return id;
}
}
public class UserQueryVO {
//查询所有用户
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//查询商品信息
//查询所有物流
}
2.Mapper代理
public interface UserMapper {
// 1、根据用户ID来查询用户信息;
public User findUserById(int id) throws Exception;
// 2、根据用户名称来模糊查询用户信息列表;
public List<User> findUserByName(String name) throws Exception;
// 3、添加用户;
public void insertUser(User user) throws Exception;
//查询用户信息
public List<User> findUserList(UserQueryVO vo) throws Exception;
//综合查询用户总数
public int findUserCount(UserQueryVO vo);
}
3.SQLMapper.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>
<!-- 配置mybatis的环境信息 -->
<environments default="development">
<environment id="development">
<!-- 配置JDBC事务控制,由mybatis进行管理 -->
<transactionManager type="JDBC"></transactionManager>
<!-- 配置数据源,采用mybatis连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value=
"jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
4.UserMapper.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.cjw.mybatis.mapper.UserMapper">
<!-- 综合查询:查询用户列表-->
<select id="findUserList" parameterType="com.cjw.mybatis.po.UserQueryVO" resultType="user">
SELECT count(1) FROM USER
<!-- where标签:默认去掉后面第一个人AND,如果没有参数,则把自己干掉 -->
<where>
<!-- if标签:可以对输入的参数进行判断 -->
<!-- test标签:指定判断表达式 -->
<if test="user != null">
<if test="user.sex != null and user.sex != ''">
AND sex = #{user.sex}
</if>
<if test="user.username != null and user.username != ''">
AND username LIKE '%${user.username}%'
</if>
</if>
</where>
</select>
<!-- 综合查询:用户总数 -->
<select id="findUserCount" parameterType="com.cjw.mybatis.po.UserQueryVO" resultType="int">
SELECT count(*) FROM USER WHERE
sex = #{user.sex} AND username
LIKE '%${user.username}%'
</select>
</mapper>
5.测试类
public class UserMapperTest {
// 声明全局的SqlSessionFactory
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUp() throws Exception {
// 1、读取配置文件
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 2、根据配置文件创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserList() throws Exception {
// 创建UserMapper对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 由mybatis通过sqlsession来创建代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserQueryVO vo = new UserQueryVO();
User user = new User();
// user.setUsername("东哥");
// user.setSex("1");
vo.setUser(user);
List<User> list= mapper.findUserList(vo);
System.out.println(list);
//关闭资源
sqlSession.close();
}
@Test
public void findUserCount() throws Exception {
// 创建UserMapper对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 由mybatis通过sqlsession来创建代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
UserQueryVO vo = new UserQueryVO();
User user = new User();
user.setUsername("东哥");
user.setSex("1");
vo.setUser(user);
int count= mapper.findUserCount(vo);
System.out.println(count);
//关闭资源
sqlSession.close();
}
}
package com.cjw.mybatis.po;
public class UserQueryVO {
//查询所有用户
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
//查询商品信息
//查询所有物流
}
二、SQL片段
<!-- 定义SQL片段
sql片段内,可以定义SQL语句中的任何部分 ,
最好不要把where和select关键字声明在内
-->
<sql id="whereClause">
<if test="user != null">
<if test="user.sex != null and user.sex != ''">
AND sex = #{user.sex}
</if>
<if test="user.username != null and user.username != ''">
AND username LIKE '%${user.username}%'
</if>
</if>
</sql>
<!-- 综合查询:查询用户列表-->
<select id="findUserList" parameterType="com.cjw.mybatis.po.UserQueryVO" resultType="user">
SELECT count(1) FROM USER
<where>
<!-- 引入SQL片段 -->
<include refid="whereClause"></include>
</where>
</select>
三、Foreache
<!-- 定义SQL片段
sql片段内,可以定义SQL语句中的任何部分 ,
最好不要把where和select关键字声明在内
-->
<sql id="whereClause">
<if test="user != null">
<if test="user.sex != null and user.sex != ''">
AND sex = #{user.sex}
</if>
<if test="user.username != null and user.username != ''">
AND username LIKE '%${user.username}%'
</if>
</if>
<!-- and id in {#{id},#{id},#{id}} -->
<!-- collection:表示POJO中集合属性的属性名称
item:为遍历出的结果声明一个变量名称
open:遍历开始时需要拼接的字符串
close:遍历结束时需要拼接的字符串
separator:遍历中间需要拼接的连接符
-->
<if test="idList !=null">
and id in
<foreach collection="idList" item="id" open="{"
close="}" separator=",">
#{id}
</foreach>
</if>
</sql>
<!-- 综合查询:查询用户列表-->
<select id="findUserList" parameterType="com.cjw.mybatis.po.UserQueryVO" resultType="user">
SELECT count(1) FROM USER
<where>
<!-- 引入SQL片段 -->
<include refid="whereClause"></include>
</where>
</select>