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);
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务