Six, MyBatis 동적 SQL

1. 의미 :
동적 SQL은 매개 변수 데이터를 기반으로 SQL을 동적으로 구성하는 기술을 말합니다.

둘째, 동적 SQL의 응용 프로그램 시나리오 :의 경우
. 예를 들어, Taobao의에 검색 할 때, 당신이 동적으로 실시간 쿼리에 대한 브랜드 등의 추가 옵션을 선택할 수 있습니다
여기에 사진 설명 삽입
셋째, 구성

  • 방법 1 :
  • 참고 : 기호보다 덜를 구성 할 때, 당신은 쓰기를 직접 할 수없는 < , 당신은 작성해야 & LT;
<?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>
  • 방법 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>

구성 매개 변수를 마음대로 변경할 수 있습니다. 예를 들어 위의 xml 파일에 두 개의 쿼리 제약 조건을 구성했습니다. 테스트 할 때이 두 매개 변수에 값을 할당하거나 할당하지 않을 수 있으므로 매우 유연합니다.

 @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);
        }
    }
}

추천

출처blog.csdn.net/qq_36792120/article/details/112404339