MyBatis의 강력한 기능 중 하나는 일반적으로 동적 SQL 기능입니다. JDBC 또는 기타 유사한 프레임 워크를 사용한 경험이 있다면 SQL 문자열을 조건부로 함께 연결하는 것이 얼마나 고통 스러운지 이해하고 목록 끝에서 공간을 잊거나 쉼표를 생략 할 수 없도록하십시오. 동적 SQL 은이 통증을 철저히 처리 할 수 있습니다.
동적 SQL
Mybatis의 동적 SQL은 SQL 스트링 스 플라이 싱의 통증을 해결합니다.
1. IF
<select id = "select id ="findActiveBlogwithTitLelike "ParameterType ="blog "resultType ="blog "> select * from blogwhere state = 'active'<if test ="title! = null "> 및 #{title} </if> </select> </select> </select> 이 문장은 선택적 텍스트 검색 기능을 제공합니다. 제목이 전달되지 않으면 활성화 된 모든 블로그가 반환됩니다.
제목이 통과되면 비슷한 제목을 찾을 수 있습니다.
2. 언제, 그렇지 않으면 선택하십시오
<select id = "findActiveBlog like"parameterType = "blog"resultType = "blog"> select * from blogwhere <selectwhere <select> <title! = null "> 및 #{title} </when </when </when </author.name! = null"> 및 auder.name} </way </way </way} 1 </그렇지 않으면> </선택> </select> 참고 : 위의 조건 중 어느 것도 일치하지 않으면 Blog Where에서 SELECT *가됩니다.
두 번째 경기 만 있으면 SELECT *에서 Blog Where 및 Title Somelike와 같은 제목이됩니다.
분명히 이것은 쿼리에 실패 할 것입니다. 이 문제를 해결하기 위해 Mybatis는 솔루션을 제공합니다.
<select id = "findActiveBlog like"parametertype = "blog"resultType = "blog"> blogwhere에서 선택 * 선택 * <trim prefix = "where"prefixoverrides = "및 | 또는"> <선택> <test = "title! = null"> 및 title} </when> <author! = null! = null! = null ". #{author.name} </when> <sygry> and feactured = 1 </elose> </선택> </trim> </select>Overrides 속성은 파이프 텍스트 분리기로 재정의되며 빈 공간이 여기에서 중요합니다. 결과는 InnerText에서 Overrides에 지정된 컨텐츠를 제거하는 것입니다.
3. 세트
<Update id = "updudeauthorifnecessary"parametertype = "author"> update author <set> <set> <if test = "username! = null"> username =#{username}, </if> < "password! = null"> password =#{password}, </if> if test = </if> </if> </if> </if " id =#{id} </update>최적화 후 위와 동일한 문제 :
<Update id = "updudeauthorifnecessary"parametertype = "author"> update audert <trim prefix = "where"prefixoverrides = ","> <set> <if test = "username! = null"> username =#{username}, </if> <null "> </if> <"</if> < "</if> <"</if> < " null "> email =#{email} </if> </set> 여기서 id =#{id} </trim> </update>위의 것은 편집자가 소개 한 SQL 문자열의 Mybatis 동적 스 플라이 싱 문제입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!