マッパー用の組み込みメソッド
モデルレイヤーは、データベースのテーブルに対応するエンティティクラスです。コントローラーレイヤーはサーブレットであり、主にビジネスモジュールプロセスの制御を担当し、サービスインターフェイスメソッドを呼び出し、Struts2はアクションです。サービスレイヤーは主に論理的な判断を行い、DAOレイヤーはデータベースに接続するデータアクセスレイヤーです。 Mapperについては、MapperマッピングファイルがDAOレイヤーで使用されます。
以下は、マッパーの組み込み方法の説明です。
1。CountByexample===>条件に応じて数量をクエリします
int countbyexample(userexampleの例); //以下は完全なケースリストです。 userexample example = new userexample();基準基準= example.createCriteria(); Criteria.andusernameequalto( "Joe"); int count = userdao.countbyexample(例);
相当:ユーザーからcount(*)を選択します。ここでusername = 'joe'
2。DeleteByExample===>条件に応じて複数のアイテムを削除します
int deletebyexample(accountexampleの例); //以下は完全なケースですuserexampleの例= new userexample();基準基準= example.createCriteria(); Criteria.andusernameequalto( "Joe"); userdao.deletebyexample(例);相当:ユーザー= 'joe'を削除するユーザーから削除
3。DeleteByPrimaryKey===>条件に応じて単一のアイテムを削除します
int deleteByPrimaryKey(integer id); userdao.deletebybyprimarykey(101);
相当:
id = 101でユーザーから削除します
4。挿入===>データを挿入します
int insert(アカウントレコード); //以下は完全なケースユーザーユーザー= new user(); //user.setid(101); user.setUsername( "test"); user.setPassWord( "123456")user.setemail( "[email protected]"); userdao.insert(user);
相当:
ユーザー(ID、ユーザー名、パスワード、電子メール)値(101、 'TEST'、 '123456'、 '[email protected]');
5。INSERTSEECTITION===>データを挿入します
int insertSelective(アカウントレコード);
6。SelectByExample===>条件に基づいてデータをクエリします
List <Account> SelectByExample(AccountExampleの例); //以下は完全なケースですuserexampleの例*ユーザーからusername = 'joe'とusernameはusername ascでnull orderです。メールdesc // note:ibatorによって生成されたファイルuserexample.javaには、静的な内部クラス基準が含まれています。基準には、主にSQLステートメントの後にクエリ条件を定義するための多くの方法があります。
7。SelectByPrimaryKey===>プライマリキーに基づいてデータをクエリします
アカウントSelectByPrimaryKey(integer id); // select * fromユーザーwhere id = variable id
8。updatebyexampleselective ===>条件に応じてnullではない値のフィールドを更新する
int updatebyexampleselective(@param( "record")アカウントレコード、@param( "emple")accountexample example); //以下は完全なケースリストであり、userexample example = new userexample();基準基準= example.createCriteria(); Criteria.andusernameequalto( "Joe"); user user = new user(); user.setPassWord( "123"); userdao.updatebyprimarykeyselective(user、example);相当:ユーザーセットパスワード= '123 'を更新するusername =' joe '
9。updatebyexampleselective ===>条件による更新
int updatebyexample(@param( "record")アカウントレコード、@param( "例")accountexample example);
10。updateByPrimaryKeySelective ===>条件に応じた更新
int updatebyPrimaryKeySelective(アカウントレコード); //以下は完全なケースですuser user = new user(); user.setId(101); user.setpassword( "joe"); userdao.updatebyprimarykeyselective(user);
相当:
ユーザーセットパスワードを更新= 'joe'ここで、id = 101
int updatebyPrimaryKeySelective(アカウントレコード); //以下は完全なケースですuser user = new user(); user.setId(101); user.setPassWord( "joe"); userdao.updatebyprimarykeyselective(user);
相当:ユーザーセットパスワードを更新= 'joe'ここで、id = 101
11。umpdatebyprimarykey===>プライマリキーを押して更新します
int updatebyprimarykey(アカウントレコード); //次の場合は完全なケースユーザー= new user(); user.setId(101); user.setUsername( "joe"); user.setPassWord( "Joe"); user.setemail( "[email protected]"); userdao.updatebyprimarykey(user);
相当:
ユーザーを更新します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(user);
相当:
ユーザーを更新しますusername = 'joe'、password = 'joe'、email = '[email protected]'ここで、id = 101
マッパーのXML構成ファイルを解析します
MyBatisがMapperのXML構成ファイルをどのように読み取って、その中のSQLステートメントを解析するかを見てみましょう。
このようなsqlsessionFactoryを構成したことを覚えています。
<bean id = "sqlsessionfactory"> <プロパティ名= "dataSource" ref = "datasource"/> <プロパティ名= "configlocation" value = "classpath:configuration.xml"> </パイプロパティ> <プロパティ名= "mapperlocations" value = "classpath:com/xxx/mybatis/maperis/mappage 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(Exception e){新しいNestedioException( "マッピングリソースの解析に失敗しました: '" + mapperlocation + "'"、e); }最後に{errorcontext.instance()。reset(); } if(logger.isdebugenabled()){logger.debug( "解析されたマッパーファイル: '" + mapperlocation + "'"); }}}MyBatisは、XMLMapperBuilderクラスのインスタンスを使用して、マッパー構成ファイルを解析します。
public xmlmapperbuilder(リーダーリーダー、構成構成、文字列リソース、Map <string、xnode> sqlfragments){this(new XpathParser(Reader、true、configuration.getVariables()、new XMLMAPPERENTITYRESOLVER()、Configuration、SQLFragments); } private xmlmapperbuilder(xpathparserパーサー、構成構成、文字列リソース、map <string、xnode> sqlfragments){super(configuration); this.builderassistant = new mapperbuilderassistant(configuration、resource); this.parser = parser; this.sqlfragments = sqlfragments; this.resource = resource; }次に、システムはXMLMapperBuilderの解析方法を呼び出してマッパーを解析します。
public void parse(){//構成オブジェクトがXML構成ファイルをロードしていない場合(重複負荷を避けている場合、マッパーノードのプロパティとコンテンツが解析されているかどうか、//キャッシュ、SQL、select、select、parametermapなどのformeTemapなどの子ノードを解析するための準備をするかどうかを確認します。 if(!configuration.isresourceloaded(resource)){configurationElement(parser.evalnode( "/mapper")); configuration.addloadedResource(リソース); bindMapperFornamesPace(); } // configurationElement関数の結果マップを処理するときに処理されていない<sultsMap>ノードを解析します。 parsependingResultMaps(); // configurationElement関数のキャッシュRefを処理するときに存在しない<cache>ノードを解析します(これは、キャッシュノードが指す前にキャッシュRefがロードされると発生します)parsependingchacherefs(); //上記と同じ、キャッシュがロードされていない場合、ステートメントParsePendingStatements()の処理時に例外もスローされます。 }マッパーのXMLファイルを解析するMyBatisのプロセスはすでに非常に明白です。マッパーをどのように解析するかを見てみましょう。
private void configurationelement(xnode context){try {// mapperノード文字列名の名前空間属性を取得= context.getStringAttribute( "namespace"); if(namespace.equals( "")){throw new builderexception( "mapper's namespaceは空にすることはできません"); } //現在の名前空間BuilderAssistant.setCurrentNamesPace(namespace)を設定します。 //マッパーの<cache-ref> node cacherefelement(context.evalnode( "cache-ref"))を解析する; //マッパーの<Cache>ノードCacheElement(Context.EvalNode( "Cache"))を解析します。 //マッパーの<parametermap>ノードパラメーターマペレメント(context.evalnodes( "/mapper/parametermap"))を解析します。 //マッパーの<sultsmap> node resultMapelements(context.evalnodes( "/mapper/resultmap"))を解析する); //マッパーの<sql>ノードsqlelement(context.evalnodes( "/mapper/sql"))を解析する); // xmlStatementBuilderオブジェクトを使用して、マッパーの<select>、<secret>、<update>、<delete>ノード、// mybaitsを使用して、mappedStatement.builderクラスを使用してマッピングステートメントオブジェクトを構築します。 BuildStatementFromContext(context.Evalnodes( "Select | insert | update | delete")); } catch(Exception e){Throw new BuildErexception( "マッパーXMLのエラー解析XML。原因:" + e、e); }}configurationElement関数は、マッパーノードのほぼすべての子ノードを解析します。この時点で、MyBaitsはマッパー内のすべてのノードを解析し、いつでも使用するSQLSessionFactoryオブジェクトの構成オブジェクトに追加します。ここでは、MyBaitsがXMLStatementBuilderクラスのオブジェクトのParseStatementNode関数をどのように使用して、MapperBuilderassist ObjectのaddMappStatementを借りてマッピングステートメントを解析し、構成クラスオブジェクトに関連付ける方法について説明を追加する必要があります。
public void parsestatementnode(){// id属性文字列id = context.getStringAttribute( "id"); // databaseid属性文字列databaseid = context.getStringAttribute( "databaseid"); if(!databaseIdMatchesCurrent(id、databaseid、this.requireddatabaseid)){return; } // fetchsize属性integer fetchsize = context.getIntattribute( "fetchsize"); // Timeout属性integer Timeout = context.getIntattribute( "Timeout"); // parametermap属性文字列parametermap = context.getStringAttribute( "parametermap"); // parametertype属性文字列parametertype = context.getStringAttribute( "parametertype"); class <?> parametertypeclass = resolveclass(parametertype); // resultMap属性文字列resultMap = context.getStringAttribute( "resultMap"); // resultType属性文字列resultType = context.getStringAttribute( "resultType"); // lang属性文字列lang = context.getStringAttribute( "lang"); LanguagedRiver langdriver = getLanguagedRiver(Lang);クラス<? // resultsetType属性文字列resultSetType = context.getStringAttribute( "resultetType"); StatementType StatementType = StatementType.ValueOf(context.getStringAttribute( "StatementType"、StatementType.Prepared.ToString()); resultSettype resultSettypeenum = sloldersultSetType(resultETTYPE); string nodename = context.getNode()。getNodename(); sqlCommandType SQLCommandType = SQLCommandType.ValueOf(nodename.touppercase(locale.english)); //それは<select> node boolean select = sqlcommandtype == sqlcommandtype.select;ですか。 // flushcache属性boolean flushcache = context.getBooleanAttribute( "flushcache"、!select); // usecache属性boolean usecache = context.getBooleanAttribute( "usecache"、isselect); // result -Ordered属性boolean resultOrdered = context.getBooleAnattribute( "result -ordered"、false); // xmlincludetransformer includeparser = new xmlincludetransformer(configuration、builderassistant)を解析する前に、フラグメントを含める; includeparser.applyincludes(context.getNode()); // selectkeyを含めて削除して削除します。 ProcessElectKeynodes(id、parametertypeclass、langdriver); // sql(pre:<selectkey>および<cluding>が解析および削除された)を解析するsqlsource sqlsource = langdriver.createsqlsource(configuration、context、parameterypeclass); // resultsetsプロパティ文字列結果= Context.getStringAttribute( "resultset"); // keyPropertyプロパティ文字列keyproperty = context.getStringAttribute( "keyproperty"); // keycolumnプロパティ文字列keycolumn = context.getStringAttribute( "keycolumn"); keygenerator keygenerator; 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))? new jdbc3keygenerator():new nokeygenerator(); } builderassistant.addmappedStatement(id、sqlsource、statementtype、sqlcommandtype、fetchsize、timeout、parametermap、parametertypeclass、resulttypeclass、resultettypeeenum、flushcache、usecache、ructured、key -denerator、key -propertertry、key -propertertr結果セット); }上記のコードから、MyBaitsがXPATHを使用してマッパー構成ファイルを解析し、結果マップ、パラメーターマップ、キャッシュ、ステートメント、およびその他のノードを作成し、関連するビルダーを使用して取得したオブジェクトを構成オブジェクトに関連付けていることがわかります。この構成オブジェクトは、SQLSessionから取得できます。これは、MyBaitsがマッパーを取得する方法の問題を説明し、SQLSessionを使用してデータベースを操作するときにSQLステートメントを実行します。