Spring MyBatis、特にデータソースを統合するプロセスにはいくつかの統合方法があるためです。私はしばしば異なる構成方法を見て、いつも少し厄介だと感じているので、今日それらを要約する時間があります。
1. org.mybatis.spring.mapper.mapperscannerconfigurerを使用します
実際、これはリバースエンジニアリングと同じ方法です
1。データソース構成ファイル
2。DAOファイル
パッケージcom.jdd.mapper; com.jdd.pojo.employeeをインポートします。 java.util.listをインポートします。 public Interface employemapper {public Employee GetemployeeByid(int id);パブリックリスト<EmployeeR> FindAlleMployees(); }3。mapper.xmlファイル
<?xmlバージョン= "。" encoding = "Utf-"? parametertype = "int" resultType = "com.jdd.pojo.employee"> <![cdata [select * from Employee where id =#{id}; ]]> </select> <select id = "findallemployees" resultType = "com.jdd.pojo.employee"> <! ]]> </select> </mapper>このようにして、DAOインターフェイスをサービスクラスに直接注入できます
パッケージcom.jdd.service.impl; com.jdd.mapper.employeemapperをインポートします。 com.jdd.pojo.employeeをインポートします。 com.jdd.service.employeeserviceをインポートします。 Import org.springframework.beans.factory.annotation.autowired; org.springframework.stereotype.serviceをインポートします。 java.util.listをインポートします。 @service( "Employeingervice")Public Class EmployeeServiceImplはEmployeeService {@Autowired Private EmployeMapper EmployeMapper; @Override公務員GetemployeeByid(int id){return employeemapper.getemployeebyid(id); } @Override public list <Employee> findAllemployees(){return employeemapper.findallemployees(); }}2。抽象クラスorg.mybatis.spring.support.sqlsessiondaosupportを使用して、sqlsessionfactoryに注入します。
1。データソース構成ファイル
<?xmlバージョン= "。" encoding = "utf - "?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:p = "http://www.springframework.org/schema/p" xmlns:aop = "http://www.springframework.org/schema/tx" xmlns:xsi = "http://ww.w.w.w.w.w.-- instcchma xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-..xsd http://www.springframework.org/schema/util http://www.springframework.org/ - > <コンテキスト:プロパティプレイスホルダーlocation = "classpath:resource /*。プロパティ" /> <! - データベース接続プール - > <bean id = "dataSource" Destroy-method = "close"> <プロパティ名= "$ {jdbc.driver}" " /> <property =" jdbc.url} name = "username" value = "$ {jdbc.username}" /> <property name = "password" value = "$ {jdbc.password}" /> <プロパティ名= "maxactive" value = "" /> <プロパティ名= "minidle" value = "" "" /> < /bean> < name = "configlocation" value = "classpath:mybatis/sqlmapconfig.xml"> </property> <property name = "dataSource" ref = "dataSource"> </property> <property name = "mapperlocations" value = "classpath:com/jdd/mapper/*2。BasedAoクラス
パッケージcom.jdd.dao; Import org.apache.ibatis.session.sqlsessionfactory; org.mybatis.spring.support.sqlsessiondaosupportをインポートします。 javax.annotation.resourceをインポートします。パブリックアブストラクトクラスBasedaoは、sqlsessionDaoSupportを拡張します{@Resource public void setSqlSessionFactory(sqlSessionFactory sqlsessionFactory){super.SetsQlSessionFactory(SQLSessionFactory); }}3.インターフェイスEmployeeDao.javaクラス
パッケージcom.jdd.dao; com.jdd.pojo.employeeをインポートします。 java.util.listをインポートします。パブリックインターフェイスEmployeeDao {Employee GetemployeeByid(int id); List <EmployeeR> findAllemployees(); }4。DAOは、EmployeeDaOIMPLクラスを実装します
パッケージcom.jdd.dao.impl; com.jdd.dao.basedaoをインポートします。 com.jdd.dao.employeeedaoをインポートします。 com.jdd.pojo.employeeをインポートします。 Import org.springframework.stereotype.repository; java.util.listをインポートします。 @Repository( "EmployeeDao")Public Class EmployeeDaoImpl extends Basedao emplyest employeeDao {@Override公務員GetemployeeByid(int id){return this.getSqlSession()。 } @Override public list <Employee> findAllemployees(){return this.getSqlSession()。selectlist( "com.jdd.dao.employeedao.findallemployees"); }}5。このようにして、eedeeedaoをサービスクラスに注入できます。
3. org.mybatis.spring.sqlsessionTemplateテンプレートクラスを使用します
1。データソースファイル
<?xmlバージョン= "。" encoding = "utf - "?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns:context = "http://www.springframework.org/schema/context" xmlns:p = "http://www.springframework.org/schema/p" xmlns:aop = "http://www.springframework.org/schema/tx" xmlns:xsi = "http://ww.w.w.w.w.w.-- instcchma xsi:schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-..xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-..xsd http://www.springframework.org/schema/util http://www.springframework.org/ - > <コンテキスト:プロパティプレイスホルダーlocation = "classpath:resource /*。プロパティ" /> <! - データベース接続プール - > <bean id = "dataSource" Destroy-method = "close"> <プロパティ名= "$ {jdbc.driver}" " /> <property =" jdbc.url} name = "username" value = "$ {jdbc.username}" /> <property name = "password" value = "$ {jdbc.password}" /> <プロパティ名= "maxactive" value = "" /> <プロパティ名= "minidle" value = "" "" /> < /bean> < name = "configlocation" value = "classpath:mybatis/sqlmapconfig.xml"> </property> <property name = "dataSource" ref = "dataSource"> </property> <プロパティ名= "mapperlocations" value = "classpath:com/jdd/mapper/*。 <constructor-arg index = "" ref = "sqlsessionfactory"/> </bean> </bean>2。Basedao.javaクラス
パッケージcom.jdd.dao; import org.mybatis.spring.sqlsessionTemplate; javax.annotation.resourceをインポートします。 public Abstract Class Basedao {public sqlsessionTemplate sqlsessionTemplate; @Resource public void setSQlSessionTemplate(sqlSessionTemplate sqlsessionTemplate){this.sqlsessionTemplate = sqlsessionTemplate; }} 3.インターフェイスEmployeeDao.javaクラス
パッケージcom.jdd.dao; com.jdd.pojo.employeeをインポートします。 java.util.listをインポートします。パブリックインターフェイスEmployeeDao {Employee GetemployeeByid(int id); List <EmployeeR> findAllemployees(); }4。DAOは、EmployeeDaOIMPLクラスを実装します
パッケージcom.jdd.dao.impl; com.jdd.dao.basedaoをインポートします。 com.jdd.dao.employeeedaoをインポートします。 com.jdd.pojo.employeeをインポートします。 Import org.springframework.stereotype.repository; java.util.listをインポートします。 @Repository( "EmployeeDao")Public Class EmployeeDaoimplはBasedao explements EmployeeDao {@Override公務員GetemployeeByid(int id){return sqlsessiontemplate.selectone( "com.jdd.dao.employeedao.getemployid"、id); } @Override public List <Employee> findAllemployees(){return sqlsessionTemplate.selectlist( "com.jdd.dao.employeedao.findallemployees"); }}5.これで、eedeeedaoをサービスクラスに直接注入して使用できます。
注:ここでのBeasedAoの注入はより柔軟です。また、sqlsessionFactoryを挿入してから、次のようにセッターメソッドにsqlsessionTemplateを作成することもできます。
パッケージcom.jdd.dao; Import org.apache.ibatis.session.sqlsessionfactory; import org.mybatis.spring.sqlsessionTemplate; javax.annotation.resourceをインポートします。 public Abstract Class Basedao {public sqlsessionTemplate sqlsessionTemplate; @resource public void setSqlSessionFactory(sqlSessionFactory sqlsessionFactory){sqlsessionTemplate = new sqlsessionTemplate(sqlsessionFactory); }}実際、SQLSessionDaoSupportクラスを継承したり、SQLSessionFactoryを注入したり、SQLSessionTemplateを直接注入する方法であるかどうかは、本質的に同じです。
SQLSessionFactoryを注入すると、下部にSQLSessionFactoryを介してSQLSessionTemplateも作成し、APIを介して動作します。
信じられない場合は、sqlsessiondaosupportのソースコードを見てみましょう。
// // Intellij Ideaによって.classファイルから再作成されたソースコードImport org.apache.ibatis.session.sqlsession; Import org.apache.ibatis.session.sqlsessionfactory; import org.mybatis.spring.sqlsessionTemplate; org.springframework.dao.support.daosupportをインポートします。 org.springframework.util.assertをインポートします。パブリックアブストラクトクラスsqlsessiondaosupport extends daosupport {private sqlsession sqlsession;プライベートブールexternalsqlsession; public sqlsessiondaosupport(){} public void setSqlSessionFactory(sqlsessionFactory sqlsessionFactory){if(!this.externalsqlsession){this.sqlsession = new sqlsessionTemplate(sqlsessionFactory); }} public void setSqlSessionTemplate(sqlSessionTemplate sqlsessionTemplate){this.sqlsession = sqlsessionTemplate; this.externalsqlsession = true; } public sqlsession getSqlSession(){return this.sqlsession; }保護されたvoid checkdaoconfig(){assert.notnull(this.sqlsession、 "Property 'sqlsessionFactory'または 'sqlsessionTemplate'が必要"); }}同様に、SQLSessionTemplateはSQLSessionインターフェイスを継承するため、操作に関係なく効果が同じです。
// // Intellij Ideaによって.classファイルから再作成されたソースコードjava.lang.reflt.invocationhandlerをインポートします。 java.lang.reflt.methodをインポートします。 java.lang.reflt.proxyをインポートします。 Java.sql.Connectionをインポートします。 java.util.listをインポートします。 java.util.mapをインポートします。 Import org.apache.ibatis.exceptions.persistenceException; org.apache.ibatis.executor.batchResultをインポート; org.apache.ibatis.reflection.exceptutil; Import org.apache.ibatis.session.configuration; org.apache.ibatis.session.executortypeをインポートします。 Import org.apache.ibatis.session.resulthandler; Import org.apache.ibatis.session.rowbounds; Import org.apache.ibatis.session.sqlsession; Import org.apache.ibatis.session.sqlsessionfactory; Import org.springframework.dao.support.persistenceExceptionTranslator; org.springframework.util.assertをインポートします。パブリッククラスsqlsessionTemplateはsqlsession {private final sqlsessionfactory sqlsessionfactory;プライベート最終executortype executortype;プライベート最終sqlsession sqlsessionproxy;プライベート最終PersistenceExceptionTranslator Exception Translator; public sqlsessionTemplate(sqlsessionFactory sqlsessionFactory){this(sqlsessionFactory、sqlsessionFactory.getConfiguration()。 } public sqlsessionTemplate(sqlsessionFactory sqlsessionFactory、executortype executortype){this(sqlsessionfactory、executortype、new mybatisexceptiontranslator(sqlsessionfactory.getConfiguration()。 } public sqlsessionTemplate(sqlSessionFactory sqlsessionFactory、executortype executortype、persistenceExceptionTranslator ExceptionTranslator){assert.notnull(sqlsessionFactory、 "Property 'sqlsessionFactory'が必須"); assert.notnull(executortype、 "property 'executortype'が必須"); this.sqlsessionfactory = sqlsessionFactory; this.executortype = executortype; this.exceptionTranslator = exceptionTranslator; this.sqlsessionProxy =(sqlsession)proxy.newproxyinstance(sqlsessionfactory.class.getClassLoader()、new class [] {sqlsession.class}、new SQLSessionTemplate.SQLSessionInterceptor()); } public sqlsessionFactory getSqlSessionFactory(){return this.sqlsessionFactory; } public executortype getExecutortype(){return this.executortype; } public PersistenceExceptionTranslator getPersistExceptionTranslator(){return this.exceptionTranslator; } public <t> t selectone(stringステートメント){this.sqlsessionproxy.selectone(statement); } public <t> t selectone(stringステートメント、オブジェクトパラメーター){return this.sqlsessionproxy.selectone(statement、parameter); } public <k、v> map <k、v> selectmap(string statement、string mapkey){return this.sqlsessionproxy.selectmap(Statement、MapKey); } public <k、v> map <k、v> selectmap(string stateme、object parameter、string mapkey){this.sqlsessionproxy.selectmap(statement、parameter、mapkey); } public <k、v> map <k、v> selectmap(string stateme、object parameter、string mapkey、rowbounds rowbounds){this.sqlsessionproxy.selectmap(statement、parameter、mapkey、rowbounds); } public <e> list <e> selectlist(stringステートメント){return this.sqlsessionproxy.selectlist(statement); } public <e> list <e> selectlist(string statement、object parameter){return this.sqlsessionproxy.selectlist(statement、parameter); } public <e> list <e> selectlist(stringステートメント、オブジェクトパラメーター、rowbounds rowbounds){this.sqlsessionproxy.selectlist(statement、parameter、rowbounds); } public void select(String Statement、Resulthandler Handler){this.sqlsessionProxy.Select(Statement、Handler); } public void select(String Statement、Object Parameter、Resulthandler Handler){this.sqlsessionProxy.Select(Statement、Parameter、Handler); } public void select(stringステートメント、オブジェクトパラメーター、rowbounds rowbounds、resulthandlerハンドラー){this.sqlsessionproxy.select(statement、parameter、rowbounds、handler); } public int insert(stringステートメント){return this.sqlsessionproxy.insert(statement); } public int insert(String Statement、Object Parameter){return this.sqlsessionProxy.insert(statement、parameter); } public int update(stringステートメント){return this.sqlsessionproxy.update(statement); } public int update(String Statement、Object Parameter){return this.sqlsessionProxy.update(statement、parameter); } public int delete(stringステートメント){return this.sqlsessionproxy.delete(statement); } public int delete(String Statement、Object Parameter){return this.sqlsessionproxy.delete(statement、parameter); } public <t> t getMapper(class <t> type){return this.getConfiguration()。getMapper(type、this); } public void commit(){supl unsupportedoperationexception( "スプリング管理されたsqlsessionでマニュアルコミットは許可されていません"); } public void commit(boolean force){新しいUnsupportedoperationException( "Spring Managed SQLSessionで手動コミットは許可されていません"); } public void rollback(){supl unsupportedoperationexception( "スプリング管理されたsqlsessionでマニュアルロールバックは許可されていません"); } public void rollback(boolean force){supl unsupportedoperationexception( "スプリング管理されたsqlsessionでマニュアルロールバックは許可されていません"); } public void close(){新しいunsupportedoperationexception( "スプリング管理されたsqlsessionでマニュアルクローズは許可されていません"); } public void clearCache(){this.sqlsessionProxy.ClearCache(); } public configuration getConfiguration(){this.sqlsessionfactory.getConfiguration(); } public Connection getConnection(){return this.sqlsessionProxy.getConnection(); } public list <batchResult> flushStatements(){return this.sqlsessionProxy.FlushStatements(); } private class sqlsessionInterceptor InvocationHandler {private sqlsessionInterceptor(){} public object invoke(Object Proxy、Method Method、Object [] args){sqlsession sqlsession = sqlsessiontils.getsqlsession sqlSessionTemplate.this.executortype、sqlsessionTemplate.this.exceptionTranslator);オブジェクトは包装されていません。 try {object result = method.invoke(sqlsession、args); if(!sqlSessionUtils.IssQlSessionTransactional(sqlsession、sqlsessionTemplate.this.sqlsessionFactory)){sqlsession.commit(true); } unwrapped = result; } catch(throwable var){unwrapped = excepurtil.unwrapthrowable(var); if(sqlsessionTemplate.this.exceptionTranslator!= null && unrapped instance of persistenceException){sqlsessionutils.closesqlsession(sqlsession、sqlsessiontemplate.this.sqlsessionfactory); sqlsession = null; Throwable Translated = sqlSessionTemplate.this.exceptionTranslator.TransLateExceptionifPossible((persistenceException)unrapped); if(translated!= null){unwrapped =翻訳; }}スロー(スロー可能)包装されていない; }最後に{if(sqlsession!= null){sqlsessionutils.closesqlsession(sqlsession、sqlsessiontemplate.this.sqlsessionfactory); }} unrappedを返します。 }}}}要約します
上記は、MyBatisのデータソースを統合するためのいくつかの構成方法です。それがあなたに役立つことを願っています。ご不明な点がございましたら、メッセージを残してください。編集者は時間内に返信します!