Mybatis进行多条件查询之if标签
if:根据标签中的test属性所对应的表达式决定标签中的内容是否需要拼接到SQL中
1.类中的接口
public interface DynaMapper {
    /**
     * if标签进行查询
     * @param emp
     * @return
     */
    List<Emp> getEmpByCondition(Emp emp);
}
2.映射文件中的查询方法 其中1=1为防止第一个条件为空时出错
<!--List<Emp> getEmpByCondition(Emp emp);-->
    <select id="getEmpByCondition" resultType="emp">
        select * from t_emp where 1=1
        <if test="empName!=null and empName !=''">
            emp_name=#{empName}
        </if>
        <if test="age!=null and age !=''">
            and age=#{age}
        </if>
        <if test="sex!=null and sex !=''">
            and sex=#{sex}
        </if>
        <if test="email!=null and email !=''">
            and email=#{email}
        </if>
    </select>
3.进行测试
public class test02 {
    @Test
    public void testByCondition() throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("Mybatis-config.xml");
        SqlSessionFactoryBuilder sessionFactoryBuilder=new SqlSessionFactoryBuilder();
        SqlSessionFactory sessionFactory=sessionFactoryBuilder.build(inputStream);
        SqlSession sqlSession=sessionFactory.openSession(true);
        DynaMapper dynaMapper=sqlSession.getMapper(DynaMapper.class);
        List<Emp> list = dynaMapper.getEmpByCondition(new Emp(null,null,22,null,null));
        System.out.println(list);
    }
}
 基恩士成长空间 421人发布
基恩士成长空间 421人发布
 查看20道真题和解析
查看20道真题和解析