Six, MyBatis dynamic SQL

1. Meaning:
Dynamic SQL refers to the technology of dynamically organizing SQL based on parameter data

Second, the application scenario of dynamic SQL: For
example, when searching on Taobao, you can dynamically select additional options such as brand for real-time query.
Insert picture description here
Third, configuration

  • method 1:
  • Note: When configuring the less than sign, you cannot directly write < , you must write <
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="goods">
<select id="dynamicSQL" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
    select * from t_goods
    <where>
        <if test="categoryId!=null">
            and category_id = #{categoryId}>
        </if>
        <if test="currentPrice!=null">
            and current_price &lt; #{currentPrice}
        </if>
    </where>
</select>
</mapper>
  • Method 2:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="goods">
 <select id="dynamicSQL" parameterType="java.util.Map" resultType="com.imooc.mybatis.entity.Goods">
        select * from t_goods
        where
        1=1
        <if test="categoryId!=null">
            and category_id = #{categoryId}>
        </if>
        <if test="currentPrice!=null">
            and current_price &lt; #{currentPrice}
        </if>
    </select>
</mapper>

We can change the configuration parameters at will. For example, we have configured two query constraints in the xml file above. When testing, we can assign or not assign values ​​to these two parameters, which is very flexible.

 @Test
    public void testDynamic() {
    
    
        SqlSession sqlSession = null;
        try {
    
    
            sqlSession = MyBatisUtils.openSession();
            Map map = new HashMap();
            // map.put("categoryId", 44);
            map.put("currentPrice", 100);
            List<Goods> list = sqlSession.selectList("goods.dynamicSQL", map);
            for (Goods goods:list){
    
    
                System.out.println(goods.getGoodsId()+"-"+goods.getTitle()+"-"+goods.getCurrentPrice());
            }
                sqlSession.commit();
        } catch (Exception e) {
    
    
            sqlSession.rollback();
        } finally {
    
    
            MyBatisUtils.closeSqlSession(sqlSession);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_36792120/article/details/112404339