Ibatis 소개 :
Ibatis는 Apache의 오픈 소스 프로젝트 및 O/R 매핑 솔루션입니다. Ibatis의 가장 큰 특징은 컴팩트하고 신속하게 시작한다는 것입니다. 복잡한 기능이 너무 많지 않으면 Ibatis는 요구 사항을 충족하고 충분히 유연 할 수있는 가장 간단한 솔루션입니다. 이제 Ibatis의 이름이 Mybatis로 바뀌 었습니다.
공식 웹 사이트는 다음과 같습니다. http://www.mybatis.org/
1. 입력 매개 변수는 단일 값입니다
<delete id = "com.fashionfree.stat.accesslog.deletememberAccesslogsbefore"parameterClass = "long"> ac accesstimestamp = # value # </delete>
2. 입력 매개 변수는 객체입니다
<insert id = "com.fashionfree.stat.accesslog.memberaccesslog.insert"parameterclass = "com.fashionfree.stat.accesslog.model.memberaccesslog> 멤버 AccessLogid, Memberid, ClientIP, HttpMethod, AccessID, AccessIturl, AccessItUrl, AccessIturl, AccessIturl, AccessIturl, AccessITURL, AccessITURL, AccessITURL, AccessID, AccessID 삽입물 삽입물 extend3) 값 ( #accessLogid #, #memberid #, #clientip #, #httpMethod #, #actionId #, #requestUrl #, #accesstimestamp #, #extend1 #, #extend2 #, #extend3 #) <insert id = "com.fashionfree.ScessLog.MembScescessLog.Indert" ParameterClass = "com.fashionfree.stat.accesslog.Model.MemberAccessLog> 멤버 ACCESSLOG (AccessLogid, 멤버드, 클라이언트, httpMethod, ActionId, requestUrl, accesstimestamp, extend1, extend2, extend3) values ( #accesslogid #, # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #멤버 #. #ActionId #, #requestUrl #, #access -timeStamp #, #extend1 #, #extend2 #, #extend3 #) </insert>
3. 입력 매개 변수는 java.util.hashmap입니다
<id = "com.fashionfree.stat.accesslog.selectactionIdAndActionNumber"ParameterClass = "hashMap"resultMap = "getActionIdAndActionNumber"> acceps (*)는 memberID = # memberID # 및 accesstimestamp <= # select <= # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # id = "com.fashionfree.stat.accesslog.SelectActionIdAndActionNumptionNumptionNumber"ParameterClass = "HashMap"resultMap = "getActionIdAndActionNumber"> ac
4. 입력 매개 변수에는 배열이 포함됩니다
<insert id = "hashmap"> hashmap "> 업데이트 질문 상태 = # 상태 # # 상태 # <dynamic propend ="QuestionId in "> <isnotnull property ="actionIds "> <accepid ="actionId "("close = ")"continction = ","> </isAction> </insert> <insert id = "updateStatusBatch"ParameterClass = "HashMap"> 업데이트 질문 상태 = # 상태 # <Dynamic Propend = "QuestionId in"> <istonnull 속성 = "actionIds"> <iterate property = "actionIds"aceniid = "("close = ")"Conjunction = "> #ActionIDs [] </iterate> </istent> </dynamic> </insert>설명 : ActionIds는 전달 된 배열의 이름입니다. 배열이 비어있을 때 SQL 문 구문 오류를 피하려면 동적 태그를 사용하십시오. 배열이 null 일 때 iBatis 구문 분석 오류를 피하기 위해 ISNOLL 태그를 사용하십시오.
5. 전달 매개 변수에는 하나의 배열 만 포함됩니다
< "com.fashionfree.stat.accesslog.model.statMemberAction.StatMemberAction.SelectActionIdsOfModule"hashMap "> statmemberAction에서 moduleId, actionId select <dynamic prevend ="select <ac </select> <select> <select> <select> <select> <select> <select> <select> <select> <select> <com.fashionfree.stat.ccesslog.model.statmemberAction.StatMemberAction.StatMemberAction.SelectCaptionIdsOfModule "resultClass ="hashmap "> select moduleId, statmemberAction에서 actionId <dynamic prepend ="</itrate = "</ousrate =" moduleId </select>
참고 : Select Tag에는 ParameterClass 항목이 없습니다.
또한 : 배열을 여기에 해시 맵에 넣을 수도 있지만 추가 오버 헤드를 추가하고 사용하지 않는 것이 좋습니다.
6. IBATIS를 매개 변수를 문자열로 직접 구문 분석하십시오
<id = "com.fashionfree.stat.accesslog.selectsumdistInctCountofaccessMemberNum"ParameterClass = "hashmap"resultClass = "int"> ac id = "com.fashionfree.stat.accesslog.selectsumdistInctInctCountofAccessMemberNum"ParameterClass = "HashMap"resultClass = "int"> SELECT COUNT (CORVERT MEMBERID) ACCESSTIMESTAMP> = # 시작 # 및 ACCESSTIMSPAMP < # end # 및 ActionID </select in $ </select </actureD #.
참고 :이 방법을 사용할 때 SQL 주입의 위험이 있으며이를 사용하는 것이 좋습니다.
7. PAGEDQUERY
<select id = "com.fashionfree.stat.accesslog.selectmemberAccesslogby"parameterClass = "HashMap"resultMap = "memberAccessLogMap"> <refid = "selectAllSql"/> <포함 refid = "wheresql"/> <select> <select> <select> <select> <select> <select> <select> <select> <select> <select> < id = "com.fashionfree.stat.accesslog.selectmemberaccesslogby.count"parameterclass = "hashmap"resultclass = "int"> include refid = "countsql"/> <포함 refid = "wheresql"/> </select> <sql id = "selectAllsql"> champledlogid, memberiD, clentip, chamesid, clentiplogid. ActionId, requestUrl, accesstimestamp, extend1, extend2, emperaCcessLog </sql> <sql id = "wheresql"> accesstimestamp <= accectimestamp # # accesstimestamp # </sql> <sql id = "countsql"> seel select count (*)> <sql </sql>)에서 secl id = "countsql">)에서 extend3. memberAccessLog </sql> <sql id = "wheresql"> accesstimestamp <= accecesslog </sql> <sql id = "pagesql"> Limit # startIndex #, # pagesize # </isnotnull> </isnotnull> </dynamic> </sql> <select id = "com.fashionfree.stat.accesslog.selectmemberAccessLogby"parameterClass = "hashmap"resultmap = "hashmap"resultmap = "memberaccesslogmap"> <selectall invicate reallalls includay refid = "wheresql"/<포함 refid = "pagesql"/> </select> </select> <select id = "com.fashionfree.stat.accesslog.selectmemberaccesslogby.count"parameterclass = "hashmap"resultclass = "int"> include refid = "countsql"/> id = "selectAllSql"> select accessLogId, 멤버, clientip, httpMethod, accepId, requestUrl, accessTimestamp, extend1, extend3, extend3, emperAccessLog </sql> <sql id = "wheresql"> accesstimestamp <= # accesstimestamp # </sql> <sql ">) MemberAccessLog </sql> <sql id = "pagesql"> <dynamic> <isnotnull property = "startIndex"> <isnotnull property = "pagesize"> limit # startIndex #, # pagesize # </isnotnull> </sql>
참고 :이 예에서는 코드가 다음과 같습니다.
Hashmap Hashmap = New Hashmap (); hashmap.put ( "accesstimestamp", somevalue); pagedQuery ( "com.fashionfree.stat.accesslog.selectmemberaccesslogby", hashmap);
pagedQuery 메소드는 먼저 com.fashionfree.stat.accesslog.selectmemberaccesslogby.count sql 쿼리를 수행하고 com.fashionfree.stat.accesslog.selectmemberAccesslogby query의 레코드 수를 얻은 다음 필요한 page sql query를 수행합니다. (com.fashionfree.stat.accesslog.SelectMemberAccessLogby). 특정 프로세스는 Utils 클래스의 관련 코드를 참조하십시오.
8. SQL 문에는 부호보다 크고 부호보다 적고 부호 <1보다 작습니다. 부호보다 크고 부호보다 작습니다.
<delete id = "com.fashionfree.stat.accesslog.deleteMemberAccessLogsbefore"ParameterClass = "long"> ac ac
XML의 CDATA 영역에 특수 문자를 배치하십시오.
<delete id = "com.fashionfree.stat.accesslog.deleteMemberAccessLogsbefore"parameterClass = "long"> <! ParameterClass = "long"> <!
첫 번째 방법을 사용하고 <and>로 작성하는 것이 좋습니다 (XML은 CDATA의 내용을 구문 분석하지 않으므로 CDATA에 동적 태그가 포함되어 있으면 작동하지 않습니다).
9. 포함 및 SQL 태그는 쉽게 공유하기 위해 일반적인 SQL 문을 함께 구성합니다.
<sql id = "selectbasicsql"> select select select select select select select select select select select select select select select select select select select select timeStamp, onlineNum, 연도, 월, 주, 일, 시간, sql> <sql id = "wheresqlbefore"> samplingtimestamp <= # samplingtimestamp # </sql> <select id = "com.fashionfree.accesslog.SelectOnlinEnlineMemberNumsBeforEsamplingTimeStamp"parameterClass = "hashmap"resultClass = "onlinememberNum"> <include refid = "selectbasicsql" /<포함 refid = "wheresqlbefore" />> <sql id = "selectBasicql"> Onlinemembernum의 샘플링 샘플링, onlinenum, 연도, 월, 주, 일, 시간 </sql> <sql id = "wheresqlbefore"> where samplingtimestamp <= # samplingtimestamp # </sql> <select id = "com.fashionfree.accesslog.selectonlinementmembsforesamplingtimeStamp" ParameterClass = "Hashmap"resultClass = "OnlinEmemberNum"> <refid = "selectbasicsql" /> <포함 refid = "wheresqlbefore" /> < /select>
참고 : SQL 태그는 참조에만 사용할 수 있으며 매핑 된 문으로 간주 될 수 없습니다. 위의 예에서와 같이 SelectBasicsQL이라는 SQL 요소가 있으며, 실행하기 위해 SQL 문으로 사용하는 것은 잘못입니다.
sqlmapclient.queryforlist ( "selectbasicsql"); ×
10. 레코드를 무작위로 선택합니다
<sql id = "randomsql"> rand () 제한 # 번호 # </sql>의 주문
데이터베이스에서 숫자 레코드를 무작위로 선택하십시오 (MySQL에만 해당)
11. 그룹화에 의해 SQL 그룹의 스티치 필드
<SQL ID =”SelectGroupBy> SELECT A.ANSWERERCTRATIONID, A.ANSWERERCATETORYID, A.ANSWERERID, A.ANSWERERNAME, A.QUESTIONCATEGORYID, A.SCORE, A.ANSWEREDNUM, A.CORRECTNUM, A.ANSWERSECONDS, A.CREATEDTIMESTAMP, A.LASTIONSPORVED, A.LASTMODIFIFID, GROUP_COTERY (Q.CATECTION) categoryName FROM AnswererCategory a, QuestionCategory q WHERE a.questionCategoryId = q.questionCategoryId GROUP BY a.answererId ORDER BY a.answererCategoryId </sql><sql id=”selectGroupBy> SELECT a.answererCategoryId, a.answererId, a.answererName, a.questionCategoryId, a.score, a.answeredNum, A.CorrectNum, A.Anwerseconds, A.CreatedTimestamp, A.LastQuestionApprovedTimestamp, A.LastModified, Group_Concat (Q.CategoryName) AnswerCategory A의 범주 이름으로 A.QuestionCategoryID = Q.QuestionCategoryD Group의 arecategory group </s chategorid </s checateid </SATERID </SATERID GROP.
참고 : MySQL의 Group_Concat 함수는 SQL에서 사용됩니다
12. IN의 순서대로 정렬하십시오
mysql :
<sql id =”GroupByInarea”> moduleId, moduleName, modulEname, 상태, lastModifierId, lastModifiedName, statModule에서 마지막으로 moduleID에서 (3, 5, 1) 주문별로 moduleId에서 lastModified ( ', 3,5,1,', ','+ltrim (moduleId)+',') <sql id = ", groupByInArea, '> moduleName, status, last -modifierid, lastModifiedName, (3, 5, 1) instr ( ', 3,5,1,', ',', '+ltrim (moduleId)+', ') </sql>
②sqlserver :
<sql id =”GroupByInarea”> moduleId, modulEname, moduleName, 상태, lastModifierId, lastModifiedName, statModule에서 lastModule (3, 5, 1) charIndex ( ',', ','+ltrim (moduleid)+',', ', 3,5,1,')에서 lastmodified에서 최종 수정되었습니다. moduleid, moduleName, status, lastmodifierid, lastModifiedName, statModule에서 lastModule (3, 5, 1) charIndex ( ','+ltrim (moduleId)+',', ', 3,5,1,') </sql>의 lastmodified.
설명 : 쿼리 결과는 IN List (3, 5, 1)의 ModuleID 순서대로 반환됩니다.
mysql : instr (str, substr)
sqlserver : charindex (substr, str) 문자열 str ltrim (str)에서 하위 문자열의 첫 번째 발생 위치를 반환합니다.
13. ResultMap resultmap은 SQL 쿼리의 열 값을 매핑 할 책임이 있습니다.
<resultmap id = "getActionIdAndActionNumber"> <결과 열 = "actionId"속성 = "actionId"jdbctype = "bigint"javatype = "long"/> <count "property ="count "jdbctype ="int "javatype ="int "/> </resultmap> xml code = getActionDand rencation"> 열 = "actionId"property = "actionId"jdbctype = "bigint"javatype = "long"/> <결과 열 = "count"property = "count"jdbctype = "int"javatype = "int"/</resultmap>
resultmap의 사용을 명시적인 결과 매핑이라고하며 resultClass (인라인 결과 매핑)에 해당합니다. resultClass를 사용하면 가장 큰 장점은 간단하고 편리하다는 것입니다. 지정된 결과를 표시 할 필요는 없습니다. Ibatis는 반성에 근거한 결정을 결정합니다. resultMap은 JDBCTYPE 및 JAVATYPE를 지정하여 더 엄격한 구성 인증을 제공 할 수 있습니다.
14. 유형
<FANDEALIAS ALIAS = "MEMBERONLINEDURE"TYPE = "COM.FASHINGFREE.STAT.ACCESSLOG.MODEL.MEMBERONLINEDURATION" /> <tondealias>
지나치게 긴 이름의 반복적 인 입력을 피하기 위해 별칭을 정의 할 수 있습니다.
15. remap
<testforRemap "ParameterClass ="hashmap "resultClass ="HashMap "remapResults ="true "> userId <isequal property ="tag "compralevalue ="1 ">, 사용자 이름 </isequal> <isequal property ="tag "compareValue ="2 ">, userpassword </isequal> </select> id = "testforRemap"ParameterClass = "HashMap"resultClass = "HashMap"remapResults = "true"> select userId <isequal property = "tag"compressValue = "1">, username </isequal> <isequal property = "tag"compareValue = "2">, userPassword </select>에서 </select>.
이 예에서는 매개 변수 태그의 값에 따라 다른 결과 세트가 얻어집니다. remapresults = "true"속성이없는 경우 ibatis는 첫 번째 쿼리 중에 결과 세트를 캐시합니다. 결과 세트 매핑은 다음에 수행되지 않지만 (여전히 프로세스에 있어야 함) 캐시 된 결과 세트가 사용됩니다.
따라서 위의 예에서 Remapresult가 기본 허위 속성이고 프로그램이 다음과 같이 작성됩니다.
Hashmap <String, Integer> Hashmap = New Hashmap <String, integer> (); hashmap.put ( "tag", 1); sqlclient.queryforlist ( "testforremap", hashmap); hashmap.put ( "tag", 2); sqlclient.queryforlist ( "testforremap", hashmap);
자바 코드
Hashmap <String, Integer> Hashmap = New Hashmap <String, integer> (); hashmap.put ( "tag", 1); sqlclient.queryforlist ( "testforremap", hashmap); hashmap.put ( "tag", 2); sqlclient.queryforlist ( "testforremap", hashmap);
이 프로그램은 마지막 쿼리를 실행할 때 오류를보고합니다. 그 이유는 iBatis가 첫 번째 쿼리의 결과 집합을 사용하고 첫 번째 및 마지막 두 번의 결과 세트는 (userId, username) 및 (userId, userPassword)가 다르기 때문에 오류가 발생하기 때문입니다. remapresults = "true"속성을 사용하는 경우 iBatis는 쿼리가 실행될 때마다 결과 매핑을 수행하므로 오류를 피할 수 있습니다 (많은 오버 헤드가 나타납니다).
16. 동적 태그의 Prepend 속성은 결과 내용에 대한 접두사로 추가됩니다. 레이블의 결과 내용이 비어 있으면 Prepend 속성이 작동하지 않습니다.
Prepend 속성이 동적 태그에 존재하면 중첩 된 자막의 첫 번째 Prepend 속성이 무시됩니다. 예를 들어:
<sql id = "wheresql"> <dynamic propend = "where"> <isnotnull property = "userId"propend = "bogus"> userId = # userId # </isnotnull> <isnotempty property = "username"prepend = "및"> username = # usernempy> </sql> </sql> id = "wheresql"> <dynamic prepend = "where"> <isnotnull 속성 = "userId"propend = "bogus"> userId = # userId # </isnotEmpy property = "username"prepend = "및"> username = # username # </isnotemmam> </sql>
이 예에서 동적 태그에는 두 개의 하위 라벨 <Isnotnull>과 <isnotempty>가 포함됩니다. 위에서 설명한 원칙에 따르면, 거짓 속성 prepend = "Bogus"가 <isonnull> 태그에 있지 않으면 동적을 제거하고 <isonepty> 태그에서 태그가 무시되어 SQL 구문 오류가 발생합니다.
참고 : 동적 태그에 Prepend 속성이 없으면 자식 태그의 첫 번째 Prepend 속성은 자동으로 무시되지 않습니다.
위는 Ibatis가 귀하에게 소개하는 데 사용되는 16 개의 SQL 문입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!