前一篇:14-Mybatis中like使用的两种情况https://blog.csdn.net/fsjwin/article/details/109674722
where部分发生变化,解决方案:mybatis提供的标签
1. if
2. where
3. foreach
下面看一下if标签的使用
1. StudentDao
//if 动态sql 必须参数为实体类,不能是其他的情况
public List<Student> selectStudentif(Student student);
2. StudentDao.xml
<select id="selectStudentif" resultType="com.yuhl.domain.Student">
select id,name,email,age from student where 1=1 and
<if test=" name != null and name != '' ">
name = #{name}
</if>
<if test="age > 10 ">
age > #{age}
</if>
</select>
3. 测试
@Test
public void test18() {
SqlSession sqlsession = MybatisUtil.getSqlsession();
StudentDao studentDao = sqlsession.getMapper(StudentDao.class);
//可以吧查询的条件放进去,也可以使用一个单独的类ParaObject类封装就可以了。
Student student = new Student(1001, "张三", "qq.com", 10);
List<Student> studentList = studentDao.selectStudentif(student);
studentList.forEach(stu -> System.out.println(stu));
}
4. 测试结果
Checking to see if class com.yuhl.vo.StudentVo matches criteria [is assignable to Object]
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 1822383117.
==> Preparing: select id,name,email,age from student where 1=1 and name = ?
==> Parameters: 张三(String)
<== Columns: id, name, email, age
<== Row: 1001, 张三, zhangsan@qq.com, 20
<== Total: 1
Student{id=1001, name='张三', email='zhangsan@qq.com', age=20}
下一篇:16-Mybatis动态sql之二 – < where>标签https://blog.csdn.net/fsjwin/article/details/109675625