if

从页面接受参数后我们会将参数打包为对象,然后将对象作为参数传给MyBatis执行查询操作,sql语句需要根据是否存在参数而动态的生成

!-- 根据姓名或cid进行搜索-->
<select id="searchProducts" parameterType="products" resultType="products">
    select *from products
where 1=1
        <if test="pname != null">
            and pname like '%${pname}%'
        </if>
        <if test="cid != null">
            and cid = #{cid}
        </if>
</select>

@Test
public void searchTest(){
    SqlSession session = factory.openSession();
    ProductsMapper mapper = session.getMapper(ProductsMapper.class);
    //查询条件对象
    Products condition = new Products();
    condition.setName("新疆");
    condition.setCid("s001");
    //执行查询
    List<Products> product = mapper.searchProducts(condition);
    System.out.println(product);
    session.close();
}
 
原文地址:https://www.cnblogs.com/huaobin/p/14162708.html