一、什么是动态sql
mybatis中 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装
如下,对用户信息查询时,对查询条件进行判断,如果输入参数不为空才进行查询条件拼接。
二、定义入参封装类
其中User类,在本分类其他博客有说明,是公共的
public class UserCustom extends User{
private static final long serialVersionUID = 1L;
}
public class UserQueryVo {
private UserCustom userCustom;
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
}
三、在mapper.xml定义
3.1定义一个sql片段,并通过条件判断进行查询
<!-- 定义sql片段 -->
<sql id="query_user_where">
<if test="userCustom!=null">
<if test="userCustom.sex!=null and userCustom.sex !=''">
and user.sex=#{userCustom.sex}
</if>
<if test="userCustom.username!=null and userCustom.username !=''">
and user.username like '%${userCustom.username}%'
</if>
</if>
</sql>
3.2引用这个动态sql
<!-- 通过性别和用户名查询 -->
<select id="findUserBySexName" parameterType="com.dd.mybatis.po.UserQueryVo" resultType="com.dd.mybatis.po.UserCustom">
select * from user
<!-- 动态sql -->
<where>
<include refid="query_user_where"></include>
</where>
</select>
四、在mqpper.java中定义
//通过性别和姓名查询
public List<UserCustom> findUserBySexName(UserQueryVo UserQueryVo) throws Exception;
五、代码测试
public class UserMapperTest {
SqlSessionFactory sqlSessionFactory;
@Before
public void before() throws Exception {
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,出入文件配置流
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void findUserBySexName() {
SqlSession sqlSession =null;
try {
sqlSession=sqlSessionFactory.openSession();
// 创建UserMapper对象,mybatis自动生成UserMapper代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
UserCustom userCustom=new UserCustom();
// 如果入参只有性别,用户名为空,将执行下面sql
// <if test="userCustom.sex!=null and userCustom.sex !=''">
// and user.sex=#{userCustom.sex}
// </if>
userCustom.setSex("1");
// 如果入参只有用户名,性别为空,将执行下面sql
<if test="userCustom.username!=null and userCustom.username !=''">
// and user.username like '%${userCustom.username}%'
// </if>
userCustom.setUsername("张三丰");
UserQueryVo userQueryVo=new UserQueryVo();
userQueryVo.setUserCustom(userCustom);
List<UserCustom> list = userMapper.findUserBySexName(userQueryVo);
System.out.println(list);
} catch (Exception e) {
// TODO: handle exception
}finally{
sqlSession.close();
}
}
}