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

相关推荐

不愿透露姓名的神秘牛友
07-11 11:21
被夸真的超级开心,好可爱的姐姐
码农索隆:老色批们不用脑补了,我把金智妮的图找来了查看图片
点赞 评论 收藏
分享
06-26 22:20
门头沟学院 Java
码农索隆:让你把简历发给她,她说一些套话,然后让你加一个人,说这个人给你改简历,然后开始卖课
我的求职精神状态
点赞 评论 收藏
分享
07-07 17:06
已编辑
深圳技术大学 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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