매퍼를위한 내장 방법
모델 레이어는 데이터베이스 표에 해당하는 엔티티 클래스입니다. 컨트롤러 계층은 주로 비즈니스 모듈 프로세스의 제어, 서비스 인터페이스 방법을 호출하고 struts2에서 작업을 담당하는 서플렛입니다. 서비스 계층은 주로 논리적 판단을하고 DAO 계층은 데이터베이스와 연결되는 데이터 액세스 계층입니다. Mapper의 경우 Mapper 매핑 파일은 DAO 레이어에 사용됩니다.
다음은 매퍼의 내장 방법에 대한 설명입니다.
1. COUNTBYEXALLE ===> 조건에 따라 수량을 쿼리하십시오
int countbyexample (userexample 예); // 다음은 완전한 사례 목록입니다. userexample example = new userexample (); 기준 기준 = example.createCriteria (); Criteria.andusernameequalto ( "Joe"); int count = userdao.countbyexample (예);
동등한 점 : 사용자 이름 = 'joe'인 사용자에서 count (*)를 선택하십시오.
2. DeleteByExample ===> 조건에 따라 여러 항목을 삭제합니다
int deletebyexample (Accountexample 예); // 다음은 완전한 CASE aserexample example = new userexample (); 기준 기준 = example.createCriteria (); Criteria.andusernameequalto ( "Joe"); userdao.deletebyexample (예); 동등한 : 사용자에서 userername = 'joe'에서 삭제
3. DeleteByPrimaryKey ===> 조건에 따라 단일 항목을 삭제합니다
int deletebyprimarykey (정수 ID); userdao.deletebyprimarykey (101);
동등한 :
id = 101 인 사용자에서 삭제하십시오
4. 삽입 ===> 데이터 삽입
int insert (계정 레코드); // 다음은 전체 CASE user user = new user ()입니다. //user.setId(101); user.setusername ( "테스트"); user.setpassword ( "123456") user.seteMail ( "[email protected]"); userdao.insert (사용자);
동등한 :
사용자 (ID, 사용자 이름, 비밀번호, 이메일) 값 (101, 'test', '123456', '[email protected]'에 삽입;
5. insertSelection ===> 데이터 삽입
int insertselection (계정 레코드);
6. selectByExample ===> 조건에 따라 데이터 쿼리
List <crack> selectByexample (Accountexample 예); // 다음은 완전한 case aserexample example = new userexample (); criteria criteria = example.createCriteria (); criteria.andusernameequalto ( "joe"); andusernameisNull (); example.setOrderByclause ( "username asc, 이메일 desc"); userDao.selectBy (sextLe); * 사용자 이름 = 'joe'및 username은 username asc에 의해 null order, email desc // usererame is user user user hose is userexample.java가 정적 내부 클래스 기준을 포함합니다. 기준에는 주로 SQL 문을 따라 쿼리 조건을 정의하기위한 많은 방법이 있습니다.
7. SelectByPrimaryKey ===> 기본 키를 기반으로 데이터 쿼리 데이터
계정 selectByPrimaryKey (정수 ID); // 선택과 동등한 * 사용자에서 id = 변수 ID
8. updateByExamplesSelective ===> 조건에 따라 값이없는 필드 업데이트.
int updateByExamplesSelective (@param ( "record") 계정 레코드, @param ( "example") accountexample 예제); // 다음은 완전한 사례 목록 aserexample example = new userexample ()입니다. 기준 기준 = example.createCriteria (); Criteria.andusernameequalto ( "Joe"); 사용자 user = 새 사용자 (); user.setpassword ( "123"); userdao.updateByPrimaryKeySelective (user, example); 동등한 : 사용자 세트 비밀번호 업데이트 = '123'여기서 username = 'joe'
9. updateByExamplesSelective ===> 조건 별 업데이트
int updatebyexample (@param ( "레코드") 계정 레코드, @param ( "example") accountexample 예제);
10. updateByPrimaryKeySelective ===> 조건에 따라 업데이트
int updateByPrimaryKeySelective (Acc
동등한 :
사용자 설정 비밀번호 = 'joe'여기서 id = 101 업데이트
int updateByPrimaryKeySelective (계정 레코드); // 다음은 완전한 케이스 user user = new user (); user.setid (101); user.setpassword ( "joe"); userdao.updateByPrimaryKeySelective (user);
동등한 : 사용자 세트 비밀번호 업데이트 = 'joe'여기서 id = 101
11. updateByPrimaryKey ===> 기본 키를 눌러 업데이트하십시오
int updateByPrimaryKey (계정 레코드); // 다음은 완전한 케이스 사용자 user = new user (); user.setid (101); user.setusername ( "Joe"); user.setpassword ( "Joe"); user.seteMail ( "[email protected]"); userdao.updatebyprimarykey (사용자);
동등한 :
사용자 세트 username = 'joe', password = 'joe', email = '[email protected]'여기서 id = 101 업데이트
int updateByPrimaryKey (계정 레코드); // 다음은 완전한 케이스 user user = new user ()입니다. user.setid (101); user.setusername ( "Joe"); user.setpassword ( "Joe"); user.seteMail ( "[email protected]"); userdao.updatebyprimarykey (사용자);
동등한 :
사용자 세트 username = 'joe', password = 'joe', email = '[email protected]'여기서 id = 101 업데이트
Mapper의 XML 구성 파일을 구문 분석합니다
MyBatis가 Mapper의 XML 구성 파일을 읽고 SQL 문을 구문 분석하는 방법을 살펴 보겠습니다.
우리는 여전히 다음과 같이 sqlsessionfactory를 구성하는 것을 기억합니다.
<bean id = "sqlsessionfactory"> <속성 이름 = "dataSource"ref = "dataSource"/> <property name = "configlocation"value = "classPath : configuration.xml"> </property name = "mapperLocations"value = "classPath : com/xxx/myBatis/mapper/*. value = "com.tiantian.mybatis.model" /> < /bean>
다음은 표현식 인 Mapperlocations 속성입니다. sqlsessionfactory는이 표현식에 따라 com.xxx.mybaits.mapper의 패키지 아래의 모든 XML 형식 파일을 읽습니다. 그렇다면이 속성을 기반으로 구성 파일을 어떻게 읽습니까?
답은 sqlsessionfactorybean 클래스의 BuildSqlSessionFactory 메소드에 있습니다.
if (! isempty (this.mapperlocations)) {for (resource mapperlocation : this.mapperLocations) {if (mapperLocation == null) {계속; } try {xmlmapperBuilder XMLMAPPERBUILDER = new XMLMAPPERBUILDER (mapperLocation.GetInputStream (), configuration, mapperLocation.toString (), configuration.getSqlfragments (); XMLMAPPERBUILDER.PARSE (); } catch (예외 e) {Throw New NestedioException ( "매핑 리소스를 구문 분석하지 못했습니다 : '" + mapperLocation + "', e); } 마침내 {errorContext.Instance (). reset (); } if (logger.isdebugenabled ()) {logger.debug ( "구문 분석 맵퍼 파일 : ' + mapperlocation +"' "); }}}MyBatis는 XMLMAPPERBUILDER 클래스의 인스턴스를 사용하여 맵퍼 구성 파일을 구문 분석합니다.
public XMLMAPPERBUILDER (리더 리더, 구성 구성, 문자열 리소스, MAP <문자열, Xnode> sqlfragments) {this (new XPathParser (Reader, True, Configuration.getVariables (), new xmlMapperentityResolver (), 구성, 리소스, SQLFragments); } private xmlmapperBuilder (XPathParser Parser, 구성 구성, 문자열 자원,지도 <String, xnode> sqlfragments) {super (configuration); this.builderassistant = 새로운 MapperBuilderAssistant (구성, 리소스); this.parser = 파서; this.sqlfragments = sqlfragments; this.resource = 자원; }그런 다음 시스템은 XMLMAPPERBUILDER의 구문 분석 방법을 호출하여 맵퍼를 구문 분석합니다.
public void parse () {// 구성 객체가 XML 구성 파일을로드하지 않은 경우 (중복로드를 피하는 경우, 맵퍼 노드의 속성과 내용이 구문 분석되었는지 확인하는 것입니다. if (! configuration.isresourceloaded (resource)) {configurationElement (parser.evalnode ( "/mapper")); configuration.addloadedResource (자원); bindmapperfornamespace (); } // configurationElemement 함수에서 resultmap을 처리 할 때 처리되지 않은 <resultmap> 노드를 구문 분석합니다. parsependingResultMaps (); // configurationElemement 함수에서 Cache-Ref를 처리 할 때 존재하지 않는 <caChe> 노드를 구문 분석합니다 (캐시 노드가 가리키기 전에 Cache-Ref가로드되면) parsependingchacherefs (); // 위와 동일, 캐시가로드되지 않으면 문을 처리 할 때 예외가 발생합니다. }Mapper의 XML 파일을 구문 분석하는 MyBatis 프로세스는 이미 매우 분명합니다. 그것이 맵퍼를 어떻게 구문 분석하는지 살펴 보겠습니다.
private void configurationElement (xnode context) {try {// 맵퍼 노드 문자열의 네임 스페이스 속성을 가져옵니다. 네임 스틱 네임 스페이스 = context.getStringAttribute ( "네임 스페이스"); if (namespace.equals ( "")) {Throw new builderException ( "Mapper 's Namespace가 비어있을 수 없음"); } // 현재 네임 스페이스 BuilderAssistant.setCurrentNamesPace (네임 스페이스)를 설정합니다. // 맵퍼의 <cache-ref> 노드 캐시 레 펠트 (context.evalnode ( "cache-ref"))를 구문 분석합니다. // Mapper의 <cache> 노드 캐시 리멘트를 구문 분석합니다 (context.evalnode ( "cache")); // Mapper의 <ParametErmap> 노드 ParametErmapElement를 구문 분석합니다 (context.evalnodes ( "/mapper/parametermap")); // Mapper의 <resultmap> 노드 resultMapElements (context.evalnodes ( "/mapper/resultmap"))를 구문 분석합니다. // Mapper의 <Sql> 노드 SqlElement (Context.evalNodes ( "/Mapper/Sql"))를 구문 분석합니다. // XMLStatementBuilder 객체를 사용하여 Mapper의 <elecling>, <insert>, <podate>, <delete> 노드를 구문 분석하여 // Mybaits는 MappedStatement.builder 클래스를 사용하여 매핑 된 스테이트 개체를 구축합니다. buildStatementFromContext (context.evalnodes ( "select | insert | update | delete")); } catch (예외 e) {throw new builderexception ( "오류 파싱 매퍼 xml. 원인 :" + e, e); }}configurationElement 함수는 Mapper 노드의 거의 모든 자식 노드를 구문 분석합니다. 이 시점에서 MyBaits는 Mapper의 모든 노드를 구문 분석하고 언제든지 SQLSESSIONFACTORY 객체의 구성 객체에 추가합니다. 여기서 우리는 Mybaits가 XMLStatementBuilder 클래스의 객체의 ParSestatementNode 기능을 사용하여 MapperBuilderAssistant 객체 BuilderAssistant의 AddMappedStatement를 빌려서 MapperBuilderAssistant BuilderAssistant를 빌려 구성 클래스와 연결하는 방법에 대한 설명을 추가해야합니다.
public void parsestatementnode () {// id 속성 문자열 id = context.getStringAttribute ( "id"); // DatabaseId 속성 문자열 databaseid = context.getStringAttribute ( "DatabaseId"); if (! databaseIdMatchEcurrent (id, databaseid, this.RequiredDatabaseId)) {return; } // fetchsize attribute 정수 fetchsize = context.getIntAttribute ( "fetchsize"); // 타임 아웃 속성 정수 시간 초과 = context.getIntAttribute ( "timeout"); // ParametErmap 속성 문자열 parameterMap = context.getStringAttribute ( "ParametErmap"); // parameterType 속성 문자열 parameterType = context.getStringAttribute ( "ParameterType"); class <?> parameterTyPeclass = resolveClass (ParameterType); // resultMap 속성 문자열 string resultMap = context.getStringAttribute ( "resultMap"); // resultType 속성 문자열 resultType = context.getStringAttribute ( "resultType"); // lang 속성 문자열 lang = context.getStringAttribute ( "lang"); LanguageDriver langdriver = getLangugedriver (Lang); class <?> resulttypeclass = resolveClass (resultType); // resultSetType 속성 문자열 resultStype = context.getStringAttribute ( "resultSetType"); stateType stateType = stateType.valueof (context.getStringAttribute ( "stateType", stateType.prepared.toString ())); resultSetType resultSetTypeenum = resolveresultsettype (resultSettype); 문자열 nodename = context.getNode (). getNodename (); sqlcommandtype sqlcommandtype = sqlcommandtype.valueof (nodename.touppercase (locale.english)); // <select> node boolean isselect = sqlcommandtype == sqlcommandtype.select; // FlushCache 속성 Boolean FlushCache = Context.GetBooleAnattribute ( "FlushCache",! isselect); // USECACHE 속성 부울 usecache = context.getBooleanAttribute ( "usecache", isselect); // resultOrdered 속성 부울 resultOrdered = context.getBooleAnattRibute ( "resultOrdered", false); // xmlincludetransformer IncludeParser = new xmlincludeTransformer (configuration, builderassistant)를 구문 분석하기 전에 단편을 포함합니다. IncludEparser.applyIncludes (context.getNode ()); // 셀렉트 키를 포함하고 제거하고 제거합니다. ProcessSelectKeynodes (ID, ParameterTypeclass, langdriver); // SQL을 구문 분석합니다 (pre : <selectkey> 및 <clenude>는 구문 분석 및 제거되었습니다) SQLSOURCE SQLSOURCE = langdriver.createsQlSource (구성, 컨텍스트, ParameterTyPeclass); // resultSets 속성 문자열 resultets = context.getStringAttribute ( "resultsets"); // keyProperty 속성 문자열 keyProperty = context.getStringAttribute ( "keyProperty"); // keyColumn 속성 문자열 keycolumn = context.getStringAttribute ( "keycolumn"); 키 게이저 키 세기 에너이터; String keystatementId = id + selectKeyGenerator.select_key_suffix; keystatementId = builderAssistant.AppLyCurrentNamesPace (keystatementId, true); if (configuration.haskeyGenerator (keystatementId)) {keygenerator = configuration.getKeyGenerator (keystatementId); } else {// usegeneratedKeys 속성 keyGenerator = context.getBooleAnattribute ( "usegeneratedKeys", configuration.isuseGeneratedKeys () && sqlcommandtype.insert.equals (sqlcommandtype)? 새로운 jdbc3keygenerator () : 새로운 nokeygenerator (); } builderAssistant.AddMappedStatement (id, sqlSource, stateType, sqlcommandtype, fetchsize, timeout, parametermap, parametertypeclass, resulttypeclass, resultSettypeenum, flushcache, usecache, resultord, keyproperty, keycolumn, databosid, datebosid, datebased, datebosidats; } 위의 코드에서 Mybaits는 XPath를 사용하여 Mapper 구성 파일을 구문 분석 한 다음 관련 빌더를 사용하여 resultMap, ParametErmap, Cache, Statement 및 기타 노드를 작성하고 얻은 개체를 구성 객체에 연결합니다. 이 구성 객체는 SQLSession에서 얻을 수 있으며, 이는 Mybaits가 데이터베이스를 작동시켜 데이터베이스를 작동 할 때 SQL 문을 실행하는 방법에 대한 문제를 설명합니다.