在 MyBatis 动态 SQL 中所做的最通用的事情是包含部分 where 字句的条件。比如:
<select id="findActiveBlogWithTitleLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG WHERE state="ACTIVE" <if test="title != null"> AND title like #{title} </if> </select>
这条语句会提供一个可选的文本查找功能。如果你没有传递 title,那么所有激活的(state="ACTIVE")博客都会被返回。但是如果你传递了 title,那么就会查找相近的 title 的博客。
假若我们想可选地搜索 title 和 author 呢?首先,要改变语句的名称让它有意义。然后简单加入另外的一个条件。
<select id="findActiveBlogLike" parameterType="Blog" resultType="Blog"> SELECT * FROM BLOG WHERE state="ACTIVE" <if test="title != null"> AND title like #{title} </if> <if test="author != null and author.name != null"> AND title like #{author.name} </if> </select>
下面示例将演示动态添加 where 语句和根据参数可选择的添加多个 where 子条件。
(1)MyBatis 配置文件 mybatis-cfg.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> <properties resource="database.properties"/> <environments default="MySqlDatabase" > <environment id="MySqlDatabase" > <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/hxstrive/mybatis/dynamic_sql/demo1/UserMapper.xml" /> </mappers> </configuration>
(2)定义 JavaBean UserBean.java,代码如下:
package com.hxstrive.mybatis.dynamic_sql.demo1; public class UserBean { private Integer userId; private String name; private String sex; private Integer age; // 忽略 getter 和 setter @Override public String toString() { return "UserBean{" + "userId=" + userId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + '}'; } }
(3)定义 Mapper 接口和 XML 文件:
a、UserMapper.java
package com.hxstrive.mybatis.dynamic_sql.demo1; import org.apache.ibatis.annotations.Param; import java.util.List; public interface UserMapper { List<UserBean> getUserList(@Param("userId") int userId); List<UserBean> getUserList2(@Param("username") String username, @Param("age") int age); }
b、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.hxstrive.mybatis.dynamic_sql.demo1.UserMapper"> <!-- 映射结果 --> <resultMap id="RESULT_MAP" type="com.hxstrive.mybatis.dynamic_sql.demo1.UserBean"> <id column="user_id" jdbcType="INTEGER" property="userId" /> <result column="name" jdbcType="VARCHAR" property="name" /> <result column="sex" jdbcType="VARCHAR" property="sex" /> <result column="age" jdbcType="INTEGER" property="age" /> </resultMap> <!-- 动态添加 where 条件 --> <select id="getUserList" resultMap="RESULT_MAP"> select `user_id`, `name`, `age`, `sex` from `user` <if test="userId > 0"> where `user_id`=#{userId} </if> </select> <!-- 动态添加可选条件(用户名和年龄)--> <select id="getUserList2" resultMap="RESULT_MAP"> select `user_id`, `name`, `age`, `sex` from `user` where `user_id` is not null <if test="username != null and username != ''"> and `name` like #{username} </if> <if test="age > 0"> and `age` > #{age} </if> </select> </mapper>
(4)客户端代码如下:
package com.hxstrive.mybatis.dynamic_sql.demo1; 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 java.io.InputStream; import java.util.List; public class DynamicSqlDemo { public static void main(String[] args) throws Exception { String cfgName = "com/hxstrive/mybatis/dynamic_sql/demo1/mybatis-cfg.xml"; InputStream input = Resources.getResourceAsStream(cfgName); SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlFactory = factoryBuilder.build(input); SqlSession sqlSession = sqlFactory.openSession(true); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); getUserList(userMapper); getUserList2(userMapper); } private static void getUserList(UserMapper userMapper) { System.out.println("getUserList():"); List<UserBean> userBeanList = userMapper.getUserList(1); for(UserBean userBean : userBeanList) { System.out.println(userBean); } } private static void getUserList2(UserMapper userMapper) { System.out.println("getUserList2():"); List<UserBean> userBeanList = userMapper.getUserList2("%张%", -1); for(UserBean userBean : userBeanList) { System.out.println(userBean); } } }
运行客户端代码,输出结果如下:
2020-09-09 13:10:00,916 DEBUG [org.apache.ibatis.logging.LogFactory] - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter. 2020-09-09 13:10:00,972 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-09 13:10:00,976 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-09 13:10:00,976 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. 2020-09-09 13:10:00,976 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - PooledDataSource forcefully closed/removed all connections. getUserList(): 2020-09-09 13:10:01,206 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Opening JDBC Connection 2020-09-09 13:10:01,755 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - Created connection 1263877414. 2020-09-09 13:10:01,757 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@4b553d26] 2020-09-09 13:10:01,759 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList] - ==> Preparing: select `user_id`, `name`, `age`, `sex` from `user` where `user_id`=? 2020-09-09 13:10:01,892 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList] - ==> Parameters: 1(Integer) 2020-09-09 13:10:01,937 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList] - <== Total: 1 UserBean{userId=1, name='Helen', sex='男', age=28} getUserList2(): 2020-09-09 13:10:01,941 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList2] - ooo Using Connection [com.mysql.jdbc.JDBC4Connection@4b553d26] 2020-09-09 13:10:01,942 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList2] - ==> Preparing: select `user_id`, `name`, `age`, `sex` from `user` where `user_id` is not null and `name` like ? 2020-09-09 13:10:01,944 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList2] - ==> Parameters: %张%(String) 2020-09-09 13:10:01,956 DEBUG [com.hxstrive.mybatis.dynamic_sql.demo1.UserMapper.getUserList2] - <== Total: 1 UserBean{userId=2, name='张小凡', sex='男', age=30}
仔细查看上面输出的日志信息,其中:
getUserList() 执行的 SQL 语句如下:
select `user_id`, `name`, `age`, `sex` from `user` where `user_id`=?
其中 “where `user_id`=? ” 条件是因为参数 userId 大于0动态添加的。
getUserList2() 执行的 SQL 语句如下:
select `user_id`, `name`, `age`, `sex` from `user` where `user_id` is not null and `name` like ?
其中 “and `name` like ?” 语句是因为传递的 username 参数不为空。