准备工作:
public class User {
private int id;
private String lastName;
private int sex;
14.1、if 语句
说明: if语句,可以动态的根据你的值来决定,是否需要动态的添加查询条件。
UserMapper类中的方法
public interface UserMapper {
public List queryUsersByNameAndSex(User user);
}
UserMapper配置文件中的配置
<!--
if语句
-->
<select id="queryUsersByNameAndSex" parameterType="com.bean.User" resultType="com.bean.User">
select id,last_name lastName,sex from t_user where
<!-- 我们希望动态的创建这个条件语句 -->
<if test="lastName != null">
last_name like concat('%',#{ lastName },'%')
</if>
<if test="sex == 0 or sex == 1">
and sex = #{sex}
</if>
</select>
测试代码:
@Test
public void testQueryUsersByNameAndSex() {
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper userMapper = session.getMapper(UserMapper.class);
List users = userMapper.queryUsersByNameAndSex(new User(0, “dmi”, 1));
System.out.println(users);
} finally {
session.close();
}
}
执行的结果:
14.2、where 语句
说明: where语句,可以帮我们在多个动态语句中,有效的去掉前面的多余的and 或 or 之类的多余关键字
UserMapper配置文件
更多内容请见原文,原文转载自:https://blog.csdn.net/weixin_44519496/article/details/120472293
标签:语句,第九章,UserMapper,private,sex,session,SQL,MyBatis,public From: https://www.cnblogs.com/wangchuanxinshi/p/16759935.html