때로는 SQL 문의 상태에서 일부 보안 판단이 필요합니다. 예를 들어, 특정 조건에 따라 쿼리 할 때 전달 된 매개 변수가 비어 있으면 현재 쿼리 결과가 비어있을 수 있습니다. 아마도 매개 변수가 비어 있어야 할 때 모든 정보를 찾을 수 있습니다. Oracle의 시퀀스 및 MySQL 기능을 사용하여 ID를 생성하십시오. 현재 동적 SQL을 사용할 수 있습니다. 다음은 MySQL 구문 및 함수 (예 : String Link Function Accat)입니다.
SelectKey 태그
삽입 문에서 Oracle은 종종 MySQL에서 시퀀스와 함수를 사용하여 삽입 테이블의 기본 키를 자동으로 생성 하며이 생성 된 기본 키를 반환하는 방법이 필요합니다. 이 효과는 mybatis의 selectkey 태그를 사용하여 달성 할 수 있습니다. 다음 예는 MySQL 데이터베이스 사용자 정의 기능 NextVal ( 'Student')을 사용하여 키를 생성하고 통과 된 엔티티 클래스의 StudentID 속성으로 설정하는 것입니다. 따라서이 방법을 실행 한 후 Edge는이 엔티티 클래스를 통해 생성 된 키를 얻을 수 있습니다.
<!-학생 자동 기본 키 삽입-> <insert id = "createStudEnatoKey"parameterType = "leming.student.manager.data.Model.StudEntity"keyProperty = "StudentId"> <selectKey keyProperty = "studentId"resultType = "String"Order "> selectVal (selectkey> inder incen incind in inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder inder in selectkey keyproperty = Student_tbl (Student_id, Student_name, Student_sex, Student_birthday, Student_photo, class_id, place_id) 값 ( #{wiching}, #{StudentName}, #{StudentSex}, #{windentbirthday}, #{windentphoto, javatype = byte [], jdbctype = blob, TypeHandler = org.apache.ibatis.type.blobtypehandler}, #{classid}, #{placeid}) </insert>
인터페이스 메소드를 호출하고 자동 키 생성을 얻습니다
학생 엔티티 = 신입생 (); Entity.setStudentName ( "Hello Dawn"); Entity.SetStudentSex (1); Entity.SetStudentBirthday (dateUtil.parse ( "1985-05-28")); Entity.setClassId ( "200000001"); Entity.SetPlaceID ( "70000001"); this.dynamicsqlmapper.createstudentAutokey (엔티티); System.out.println ( "신규 학생 ID :" + Entity.getStudentId ());
SelectKey 명령문 속성 구성 세부 사항 :
| 재산 | 설명하다 | 가치를 얻으십시오 |
| keyproperty | SelectKey 문에 의해 생성 된 결과에 대해 설정 해야하는 속성. | |
| 결과 유형 | 결과 유형을 생성하십시오. MyBatis는 String 및 Int 유형을 포함한 기본 데이터 유형을 사용할 수 있습니다. | |
| 주문하다 | 1 : 이전에 기본 키가 먼저 선택되면 키 프로파인이 설정되고 삽입 문이 실행됩니다. 2 : 삽입문을 먼저 실행 한 다음 SelectKey 문을 실행하십시오. | 전에 후에 |
| StateGype StateGype | Mybatis는 진술, 준비 및 호출 가능한 진술 양식, 진술, 준비된 상태 및 호출 회계 응답에 해당합니다. | 성명 준비 호출 가능 |
태그 인 경우
여러 유형의 SQL 문에서 태그를 사용할 수 있다면 쿼리를 예로 들어 봅시다. 먼저 매우 일반적인 쿼리를 살펴 보겠습니다.
<!-이름과 같은 쿼리 학생 목록-> <select id = "getStudentListlikename"parameterType = "studententity"resultMap = "studentResultMap"> select * from student_tbl st where st.student_name (concat ( '%', #{indudentname}), '%') </select> 그러나 현재 StudentName 또는 StudentSex가 NULL 인 경우이 진술은 오류를보고하거나 쿼리 결과가 비어있을 가능성이 높습니다. 현재 IF 동적 SQL 문을 사용하여 먼저 판단을합니다. 값이 빈 문자열과 무효 인 경우이 조건에 대한 판단을하지 않고 유연성을 증가시킵니다.
매개 변수는 엔티티 클래스 학생입니다. 엔티티 클래스의 모든 속성은 판단되며 비어 있지 않으면 판단 조건이 실행됩니다.
<!-2 if (판단 매개 변수)-엔티티 클래스가 조건으로 비어 있지 않은 속성을 사용하십시오-> <select id = "getStudentList_if"resultmap = "resultMap_studentity"parameterType = "liming.student.manager.data.Model.studentEntity"> select st.student_id, St.student_name, St.student_sex, select. St.student_birthday, St.student_photo, St.Class_id, St.Class_id, St.Place_id where <if test = "studentName! = null"> studentname "> St.student_name like 컨덕 트 ( '%', #{StudentName, jdbctype = varchar}), '%') </if> <if test =. "> and st.student_sex = #{StudentSex, jdbctype = integer} </if> <if> <if test ="Studentbirthday! = null "> and St.student_birthday = #{Studentbirthday, jdbctype = date} </if> <if test ="classid! = null 및 classid! #{classId, jdbctype = varchar} </if> <if test = "classentity! = null and classentity.classId! = null and classentity.classId! = ''" "> 및 St.Class_id = #{classentity.classid, jdbctype = varchar} </if> <flaceid! = null 및 plaseid! st.place_id = #{placeId, jdbctype = varchar} </if> <if test = "test ="placeentity! = null and placeEntity.placeId! = null and vaceentity.placeID! = '' "> 및 St.Place_id = #{studentId! = null and and studentId! St.student_id = #{studentId, jdbctype = varchar} </if> </select>그것을 사용할 때, 당신이 그것을 사용하려면, 당신은 새로운 엔티티 클래스의 조건을 제한해야합니다. 해당 값을 조건 위치에만 첨부하면됩니다. 반대로, 값을 할당하지 않으면 위치를 판단 할 수 없습니다.
public void select_test_2_1 () {Studententity Entity = New Studententity (); Entity.setStudentName ( ""); Entity.SetStudentSex (1); Entity.SetStudentBirthday (dateUtil.parse ( "1985-05-28")); Entity.setClassId ( "200000001"); //entity.setPlaceId("70000001 "); List <TudlyEntity> list = this.dynamicsqlmapper.getStudentList_if (Entity); for (studententity e : list) {system.out.println (e.toString ()); }}
if + 조건 판단
이러한 조합은 태그가 더 많이 사용되는 경우 조건에서 오류가 발생할 수 있습니다. Java 코드가 다음과 같이 호출 될 때 예를 들어 3.1의 쿼리 명령문을 사용해 봅시다.
@test public void select_test_2_1 () {Studententity Entity = New Studententity (); Entity.SetStudentName (NULL); Entity.SetStudentSex (1); List <TudlyEntity> list = this.dynamicsqlmapper.getStudentList_if (Entity); for (studententity e : list) {system.out.println (e.toString ()); }} 위의 예제가 NULL 인 경우 Student_Name 열은 판단되지 않으며 "WHERE 및"키워드의 추가 오류 SQL이 직접 파생됩니다.
현재 동적 진술을 사용하여 문제를 해결할 수 있습니다. 이 "여기서"태그는 포함 된 태그에 반환 값이 있으면 'where'를 삽입한다는 것을 알 수 있습니다. 또한 태그로 반환 된 컨텐츠가 시작되거나 또는 또는 또는 제거되면 제거됩니다.
위의 예는 다음으로 수정됩니다.
<!- 3 select-where/if (판단 매개 변수)- 엔티티 클래스가 위치 조건으로 비어 있지 않은 속성을 사용하십시오-> <select id = "getStudentList_whereif"resultmap = "resultmap_studentity"parametertype = "liming.student.manager.data.model.studentity"> select St.student _, St.student, St.student, St. St.student, St.student_birthday, St.student_photo, st.class_id, st.plase_id from student_tbl st <where> <where> <if test = "studentname! = null"> st.student_name like concat ( '%', #{studentname, jdbctype = varchar}), '%') ''> 및 St.Student_sex = #{StudentSex, jdbctype = integer} </if> <if> <if test = "StudentBirthday! = null"> 및 St.student_birthday = #{StudentBirthday = #{wichingbirthday, jdbctype = date} </if> if test! = null! = null! #{classId, jdbctype = varchar} </if> <if test = "classentity! = null and classentity.classId! = ''" "> and st.class_id = #{classentity.classId, jdbctype = varchar} </if> <"placeid! = null 및 placeid! jdbctype = varchar} </if> <if test = "placeEntity! = null and vaceentity.placeId! = null and placeEntity.placeId! = ''"> and st.Place_id = #{vaceNTity.PlaceId, jdbctype = varchar} </if> if test = "{student and student! jdbctype = varchar} </if> </where> </select> if + set에 대한 업데이트 문
업데이트 문에 IF 태그가 사용되지 않으면 매개 변수 NULL이 있으면 오류가 발생합니다.
업데이트 문에 IF 태그를 사용하는 경우 이전 IF가 실행되지 않으면 쉼표 중복 오류가 발생할 수 있습니다. 세트 태그를 사용하여 세트 키워드를 동적으로 구성하고 조건의 끝에 추가 된 관련없는 쉼표를 제거하십시오.
IF+SET 태그로 수정 한 후 항목이 NULL 인 경우 업데이트되지 않지만 원래 데이터베이스 값은 유지됩니다. 다음 예제 :
4 if/set (판단 매개 변수)-엔티티 클래스가 비어 있지 않은 속성 업데이트-> <업데이트 id = "updateStudent_if_set"ParameterType = "leming.student.manager.data.model.studEntentity"> update student_tbl <set> < "studentname! = null 및 studentname! #{studentName}, </if> <if test = "windentSex! = null and windentSex! = '' '"> windent_tbl.student_sex = #{windentsex}, </if> <if test = "StudentBirthDay! = null"> windent_tbl.student_birthday = {studentbirthday}, </if> if> if> if> if> < " "> Student_tbl.student_photo = #{StudentPhoto, javatype = byte [], jdbctype = blob, typehandler = org.apache.ibatis.type.blobtypehandler}, </if> <if test ="classid! = '' "> Student_tbl.class = #{classid} ! = '' ""> wident_tbl.place_id = #{placeId} </if> </set> 여기서 where where intods_tbl.student_id = #{StudentId}; </업데이트> 위치/설정 태그 대신 + 트림 인 경우
Trim은 중복 키워드 태그로 갈 수있는보다 유연한 장소로, 위치 및 세트의 효과를 연습 할 수 있습니다.
위치 대신 트림
<!-5.1 if/trim을 대체합니다. St.Place_id에서 student_tbl st <trim prefix = "where"prefixoverrides = "및 | 또는 | | if test ="studentname! = null "> st.student_name like concat (concat ( '%', #{windationname, '%') </if> if> <" '<'< '' st.student_sex = #{elitsex, jdbctype = integer} </if> <if test = "Studentbirthday! = null"> and studstudent_birthday = #{Studentbirthday = #{date} </if> <if test = "classid! = null 및 classid! jdbctype = varchar} </if> <if test = "classentity! = null and classentity.classid! = null and classentity.classId! = ''"> and st.class_id = #{classentity.classid, jdbctype = varchar} </if> if> if testiid! = null! #{placeId, jdbctype = varchar} </if> <if test = "placeentity! = null and vaceentity.placeId! = null and sternity.placeId! = ''" "> 및 St.Place_id = #{placeEntity.placeId, jdbctype = varchar} </if> if test! = null! = null! #{StudentId, jdbctype = varchar} </if> </trim> </select>
세트 대신 트림
<!-5.2 if/trim을 대체합니다 (판단 매개 변수)-엔티티 클래스가 비어 있지 않은 업데이트 속성-> <Update id = "updateStudent_if_trim"ParameterType = "leming.student.manager.data.model.studentity"> update wiching <tbl <trim prefix = "setlyname! ! = '' ""> Student_tbl.student_name = #{StudentName}, </if> <if test = "windentsex! = null and windationsex! = ''" "> Student_tbl.student_sex = #{StudentSex}, </if> <"StudentBirthday! = null "> elull"> student_tbl.studbl.studd.studtud.studtud.studtud.studtud.studbl.StudBl.Student_birthd. #{StudentBirthDay}, </if> <if test = "StudentPhoto! = null"> 학생 _tbl.student_photo = #{StudentPhoto, javatype = byte [], jdbctype = blob, typehandler = org.apache.ibatis.type.blobtyhandler}, </if test = "" "> if/if> Student_tbl.class_id = #{classId}, </if> <if test = "placeId! = ''" "> Student_tbl.place_id = #{placeID} </if> </trim> 여기서 where where where where where where where intod} </update> 선택 (그렇지 않으면)
때때로 우리는 모든 조건을 적용하고 싶지 않지만 여러 옵션 중에서 하나만 선택하십시오. IF 태그를 사용하는 경우 테스트의 표현식이 사실 인 한 IF 태그의 조건이 실행됩니다. Mybatis는 선택 요소를 제공합니다. 태그가 (and)와의 관계 인 경우, 선택한 경우 선택은 (또는)와의 관계입니다.
선택 태그는 태그가 순서대로 유효 할 때 내부의 테스트 조건을 결정하는 것입니다. 유효한 경우 선택이 끝납니다. 선택의 모든 조건이 충족되지 않으면 그렇지 않으면 SQL이 실행됩니다. Java의 스위치 명령문과 유사하게 스위치, 경우 케이스 및 기본값을 선택하십시오.
예를 들어, 다음 예제는 제한 될 수있는 모든 조건을 기록하고 사용할 수 있습니다. 선택은 태그 시점에서 테스트 true를 사용하여 SQL 실행을 선택합니다. 보안 고려 사항은 선택을 마무리하고 오류보다 더 많은 키워드를 배치하는 위치를 사용합니다.
<!-6 선택 (판단 매개 변수)-조건에서 순서대로 비어 있지 않은 엔티티 클래스의 첫 번째 속성을 선택하십시오.> < "getStudentList_choose"resultMap = "resultMap_studEntity"ParameterType = "liming.student.manager.data.model.studentity"> select st.student _id, st.student, St.student _id, st.studentity "> St.student_birthday, St.student_photo, st.class_id, st.plase_id에서 student_tbl st <here> <chelect> <test = "studentname! = null"> st.student_name like concat ( '%', #{windationname, jdbctype = varchar}), '%')) < '< "<"%'). ! = '' "> 및 St.Student_sex = #{StudentSex, jdbctype = integer} </when> <test ="studentbirthday! = null "> 및 St.student_birthday = #{windentbirthday, jdbctype = date} </when> <when test ="null 및 classid! = null! #{classId, jdbctype = varchar} </</when <test = "classentity! = null and classentity.classId! = ''"> and st.class_id = #{classentity.classid, jdbctype = varchar} </when> < "placeid! = null 및 placeid! jdbctype = varchar} </when </when <when test = "placeEntity! = null and vaceentity.placeId! = null and placeEntity.placeId! = ''"> and St.Place_id = #{placeEntity.placeId, jdbctype = varchar} </when> when test = "{student and student and studentid! jdbctype = varchar} </when> <soyp> </elose> </선택> </where> </select>
foreach
동적 SQL, 주로 조건에서 컬렉션을 반복해야합니다. 목록 인스턴스는 "목록"을 키로 사용하고 배열 인스턴스는 "배열"을 키로 사용합니다.
Foreach 요소는 매우 강력합니다. 컬렉션을 지정하고, 수집 항목 및 인덱스 변수를 선언 할 수 있으며, 이는 요소 본문 내에서 사용할 수 있습니다. 또한 개방형 및 닫힌 문자열을 지정하여 반복 사이에 분리기를 배치 할 수 있습니다. 이 요소는 매우 똑똑하며 우연히 추가 분리기를 추가하지 않습니다.
참고 : MyBatis의 매개 변수 객체로 목록 인스턴스 또는 배열을 전달할 수 있습니다. 이렇게하면 MyBatis는 이름을 키로 자동으로 랩핑합니다. 목록 인스턴스는 "목록"을 키로 사용하고 배열 인스턴스는 "배열"을 키로 사용합니다.
이 섹션은 XML 구성 파일 및 XML 매핑 파일에 대해 설명합니다. 다음 섹션에서는 Java API에 대해 자세히 설명하므로 생성 한 가장 효율적인 매핑을 얻을 수 있습니다.
1. 매개 변수의 예를 배열로 씁니다
인터페이스의 메소드 선언 :
공개 목록 <TudlyEntity> getStudEntListByClassIds_foreach_array (String [] classIds);
동적 SQL 문 :
<! — 7.1 foreach (루프 배열 매개 변수) -in in in in in in in in in in in in in in in in in in in in id id = "getStudentListByClassIds_foreach_Array"resultMap = "resultMap_studentity"> select St.student_id, st.student_name, st.student_sex, St.student_birthday, St.student_birthday, St.student_birthday, St.student_birthday voreach collection = "array"item = "classIds"open = "("seplicator = ","close = ")"> #{classIds} </foreach> </select>
200000001과 200000002의 두 클래스에서 학생들을 쿼리하기 위해 코드를 테스트하십시오.
@test public void test7_foreach () {string [] classids = { "200000001", "200000002"}; 목록 <Tudententity> list = this.dynamicsqlmapper.getStudentListByClassIds_foreach_array (classIds); for (studententity e : list) {system.out.println (e.toString ()); }} 2. 매개 변수 목록의 예를 작성하십시오
인터페이스의 메소드 선언 :
공개 목록 <TudlyEntity> getStudEntListByClassIds_foreach_list (list <string> classidList);
동적 SQL 문 :
<!-7.2 foreach (루프 목록 <String> 매개 변수)-in in in in in in in in in in in in in in in in in in id id = "getStudentListByClassIds_foreach_list"resultMap = "resultMap_studentity"> select st.student_id, st.student_name, st.student_sex, St.student_birthday, St.student_birthday, St.student_birthday, st.student_birthday, st.student_id. St.Place_id where where where st.class_id in <foreach collection = "list"item = "classidList"Open = "("seplicator = ","close = ")"> #{classidList} </foreach> </select>
200000001과 200000002의 두 클래스에서 학생들을 쿼리하기 위해 코드를 테스트하십시오.
@test public void test7_2_foreach () {arraylist <string> classidList = new ArrayList <string> (); classidList.add ( "200000001"); classidList.add ( "200000002"); 목록 <Tudententity> list = this.dynamicsqlmapper.getStudEntListByClassIds_foreach_List (classIdList); for (studententity e : list) {system.out.println (e.toString ()); }}3. 매개 변수를 직접 맵 유형으로 캡슐화합니다.
< "dynamicforeach3test"resulttype = "blog"> select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select * select where t_blog where "%" #{title} "%"및 id in <foreach collection = "index"item = "item"open = "("separator = ","close = ")") "> #{item} </foreach> </select>위의 컬렉션의 값은 ID이며, 이는 전달 된 매개 변수 맵의 키와 해당 매퍼 코드입니다.
공개 목록 <blog> dynamicforeach3test (map <string, object> params);
해당 테스트 코드 :
@test public void dynamicfireach3test () {sqlsession session = util.getsqlsessionfactory (). opensession (); Blogmapper Blogmapper = session.getMapper (blogmapper.class); 최종 목록 <integer> ids = new ArrayList <integer> (); ids.add (1); ids.add (2); ids.add (3); ids.add (6); ids.add (7); ids.add (9); map <string, object> params = new Hashmap <String, object> (); params.put ( "ids", ids); params.put ( "제목", "중국"); 목록 <blog> blogs = blogmapper.dynamicforeach3test (params); for (블로그 블로그 : 블로그) system.out.println (블로그); session.close (); }