Parce qu'il existe plusieurs méthodes d'intégration dans le processus d'intégration de MyBatis, en particulier de la source de données. Je vois souvent différentes méthodes de configuration et je me sens toujours un peu désordonné, j'ai donc le temps de les résumer aujourd'hui.
1. Utilisez org.mybatis.spring.mapper.mapperscannerconfigurer
En fait, c'est de la même manière ingénieur inverse
1. Fichier de configuration de la source de données
2. Fichier Dao
package com.jdd.mapper; import com.jdd.pojo.employee; Importer java.util.list; Interface publique EmployEemapper {employé public getEmployeeById (int id); Liste publique <Lesyilleee> findAlLemployees (); }3. Fichier Mappel.xml
<? xml version = "." Encoding = "UTF-"?> <! Doctype Mappeur public "- // mybatis.org//dtd mapper .//en" "http://mybatis.org/dtd/mybatis - mapper.dtd"> <masper namespace = "com.jddd.mapper.employeper"> <lelestr id = "GetEmp" paramètreType = "int" resultType = "com.jdd.pojo.employee"> <! [cdata [select * dans l'employé où id = # {id}; ] [ ]]> </ select> </ mapper>De cette façon, vous pouvez injecter directement l'interface DAO dans la classe de service
package com.jdd.service.impl; import com.jdd.mapper.EmployEemapper; import com.jdd.pojo.employee; Importer com.jdd.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.sterreotype.service; Importer java.util.list; @Service ("EmployingService") Classe publique Employés de l'Employés de l'Employés implémente Employés pour employés {@Autowired Private EmployEemapper EmployEmpapper; @Override Public Employee GetEmployEEBYID (int id) {return EmployEemapper.GetEmployEEById (ID); } @Override Public List <Lesyee> findAlLemployees () {return EmployEemapper.FindAlmployees (); }}2. Utilisez la classe abstraite org.mybatis.spring.support.sqlSessionDaosupport pour l'injecter dans le SQLSessionFactory.
1. Fichier de configuration de la source de données
<? xml version = "." 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://www.w.org//xmlschema instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/contex 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/schema/util/spring-util-..xsd "> <! <Context: propriété-placeholder location = "classPath: Resource / *. Properties" /> <! - Database Connection Pool -> <bean id = "dataSource" destrement-méthod = "close"> <propriété name = "driverclassName" value = "$ {jdbc.driver}" /> <propriété name = "url" value = "$ {jdbc.url}" name = "username" value = "$ {jdbc.userName}" /> <propriété name = "mot de passe" value = "$ {jdbc.password}" /> <propriété name = "maxactive" value = "" /> <propriété name = "minidle" value = "" /> </ bean> <! name = "configLocation" value = "classPath: mybatis / sqlmapconfig.xml"> </ propriété> <propriété name = "dataSource" ref = "dataSource"> </ propriété> <propriété name = "makeLocations" varie2. Classe basée
package com.jdd.dao; import org.apache.ibatis.session.sqlSessionFactory; import org.mybatis.spring.support.sqlSessionDaOSupport; import javax.annotation.resource; Public Abstract Class Basedao étend SqlSessionDaOSupport {@Resource public void SetSQLSessionFactory (SQLSessionFactory SqlSessionFactory) {Super.SetsQlSessionFactory (SQLSessionFactory); }}3. Classe d'employeedao.java
package com.jdd.dao; import com.jdd.pojo.employee; Importer java.util.list; Interface publique Employeedao {Employee GetEmployEyId (int id); Liste <employee> findAlLemployees (); }4. Dao met en œuvre la classe Employeedaoimpl
package com.jdd.dao.impl; import com.jdd.dao.basedao; import com.jdd.dao.employeedao; import com.jdd.pojo.employee; import org.springframework.sterreotype.repository; Importer java.util.list; @Repository ("Employeedao") Public Class EmployeedaOIMPL étend Basedao implémente Employeedao {@Override Public Employee GetEmployEyId (int id) {return this.getsqlSession (). SelectOne ("com.jddd.dao.employeedao.getEmployeeyId", id); } @Override Public List <Lesyee> findAlLemployees () {return this.getsqlSession (). SelectList ("com.jdd.dao.employeedao.findallemployees"); }}5. De cette façon, vous pouvez injecter Employeedao dans la classe de service.
3. Utilisez org.mybatis.spring.sqlSessionTemplate Template Classe
1. Fichier de source de données
<? xml version = "." 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://www.w.org//xmlschema instance" xsi: schemalocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-..xsd http://www.springframework.org/schema/contex 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/schema/util/spring-util-..xsd "> <! <Context: propriété-placeholder location = "classPath: Resource / *. Properties" /> <! - Database Connection Pool -> <bean id = "dataSource" destrement-méthod = "close"> <propriété name = "driverclassName" value = "$ {jdbc.driver}" /> <propriété name = "url" value = "$ {jdbc.url}" name = "username" value = "$ {jdbc.userName}" /> <propriété name = "mot de passe" value = "$ {jdbc.password}" /> <propriété name = "maxactive" value = "" /> <propriété name = "minidle" value = "" /> </ bean> <! name = "configLocation" value = "classPath: mybatis / sqlmapconfig.xml"> </ propriété> <propriété name = "dataSource" ref = "dataSource"> </ propriété> <propriété name = "mAperLocations" value = "classpath: com / jdd / mapper / *. xml"> </ propriété> </fr <Constructor-Arg index = "" Ref = "SqlSessionFactory" /> </bEAN> </bars>2. Classe de base
package com.jdd.dao; import org.mybatis.spring.sqlSessionTemplate; import javax.annotation.resource; public abstrait class basasedao {public sqlSessionTemplate sqlSessionTemplate; @Resource public void setsqlSessionTemplate (sqlSessionTemplate sqlSessionTemplate) {this.sqlSessionTemplate = sqlSessionTemplate; }} 3. Classe d'employeedao.java
package com.jdd.dao; import com.jdd.pojo.employee; Importer java.util.list; Interface publique Employeedao {Employee GetEmployEyId (int id); Liste <employee> findAlLemployees (); }4. Dao met en œuvre la classe Employeedaoimpl
package com.jdd.dao.impl; import com.jdd.dao.basedao; import com.jdd.dao.employeedao; import com.jdd.pojo.employee; import org.springframework.sterreotype.repository; Importer java.util.list; @Repository ("Employeedao") Public Class EmployeedaOimpl étend Basedao implémente Employeedao {@Override Public Employee GetEmployEyId (int id) {return sqlSessionTemplate.Selectone ("com.jdd.dao.employeedao.getemplateeyid", id); } @Override Public List <Lesyee> findAlLemployees () {return sqlSessionTemplate.SelectList ("com.jdd.dao.employeedao.findallemployeees"); }}5. Vous pouvez maintenant injecter directement Employeedao dans la classe de service pour l'utiliser.
Remarque: L'injection de basez-basée ici est plus flexible. Vous pouvez également injecter SQLSessionFactory, puis créer SQLSessionTemplate dans la méthode du secteur, comme suit:
package com.jdd.dao; import org.apache.ibatis.session.sqlSessionFactory; import org.mybatis.spring.sqlSessionTemplate; import javax.annotation.resource; public abstrait class basasedao {public sqlSessionTemplate sqlSessionTemplate; @Resource public void setsqlSessionFactory (SQLSessionFactory SQLSessionFactory) {SQLSessionTemplate = new SQLSessionTemplate (SQLSessionFactory); }}En fait, que ce soit la méthode d'héritage de la classe SQLSessionDaosupport, d'injecter le SQLSessionFactory, ou d'injecter directement le SQLSessionTemplate, c'est essentiellement la même.
Si vous injectez SQLSessionFactory, il crée également un SQLSessionTemplate via SQLSessionFactory en bas, puis fonctionne via son API.
Si vous ne le croyez pas, laissez-moi voir le code source de SQLSessionDaOsupport:
// // Code source recréé à partir d'un fichier .class par Intellij Idea // (alimenté par Fernflower Decompiler) // package org.mybatis.spring.support; import org.apache.ibatis.session.sqlSession; import org.apache.ibatis.session.sqlSessionFactory; import org.mybatis.spring.sqlSessionTemplate; import org.springframework.dao.support.daosupport; import org.springframework.util.assert; Classe abstraite publique SqlSessionDaOSupport étend daosupport {private sqlSession sqlSession; Booléen privé ExternalsqlSession; public sqlSessionDaOsupport () {} public void setsqlSessionFactory (sqlSessionFactory sqlSessionFactory) {if (! this.externalsqlSession) {this.sqlSession = new sqlSessionSemplate (sqlSessionFactory); }} public void setsqlSessionTemplate (sqlSessionTemplate sqlSessionTemplate) {this.sqlSession = sqlSessionTemplate; this.externalsqlSession = true; } public sqlSession getsqlSession () {return this.sqlSession; } protégée void checkDaOConfig () {assert.notnull (this.sqlSession, "Property 'SqlSessionFactory' ou 'SqlSessionTemplate' sont requis"); }}De même, SQLSessionTemplate hérite de l'interface SQLSession, donc l'effet est le même indépendamment du fonctionnement.
// // Code source recréé à partir d'un fichier .class par Intellij Idea // (alimenté par Fernflower Decompiler) // package org.mybatis.spring; import java.lang.reflect.invocationhandler; import java.lang.reflect.method; import java.lang.reflect.proxy; import java.sql.connection; Importer java.util.list; importation java.util.map; import org.apache.ibatis.exception.SpersisTentenceException; import org.apache.ibatis.executor.batchResult; import org.apache.ibatis.reflection.ExceptionUtil; import org.apache.ibatis.sse.Configuration; import 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.persistencexceptionStanslateur; import org.springframework.util.assert; classe publique SQLSessionTemplate implémente SQLSession {private final sqlSessionFactory sqlSessionFactory; Executype final privé ExecutTeType; Final privé SQLSESSION SQLSESSESSEPROXY; Persistance final privée ExceptionTranslateur de persistance finale; public sqlSessionTemplate (sqlSessionFactory SqlSessionFactory) {this (sqlSessionFactory, sqlSessionFactory.getConfiguration (). GetDefaultExEcutType ()); } public sqlSessionTemplate (sqlSessionFactory sqlSessionFactory, exécutorType exécutorType) {this (sqlSessionFactory, exécutorType, new MyBatisexceptionSivertorator (sqlSessionFactory.getConfiguration (). } public sqlSessionTemplate (sqlSessionFactory sqlSessionFactory, exécutorType exécutorType, persistancexceptionStranslateur expenstranslateur) {assert.notnull (sqlSessionFactory, "Property 'sqlSessionFactory' est obligatoire"); Assert.notnull (exécutorType, "propriété 'exécutorType" est requis "); this.sqlSessionFactory = sqlSessionFactory; this.executOrType = exécutorType; this.ExceptionStRanslator = exceptionTranslator; this.sqlSessionProxy = (sqlSession) proxy.newproxyinstance (sqlSessionFactory.class.getClassLoader (), new class [] {sqlSession.class}, new sqlSessionTemplate.SQLSESSESSINGInterceptor ()); } public sqlSessionFactory getSQLSessionFactory () {return this.sqlSessionFactory; } public ExecutorType GetExecutOrType () {return this.executorType; } public persistancexceptionstranslateur getPerSistenceExceptionTranslator () {return this.ExceptionStRanslator; } public <T> t SelectOne (instruction String) {return this.sqlSessionProxy.SelectOne (instruction); } public <T> t SelectOne (instruction String, paramètre objet) {return this.sqlSessionProxy.SelectOne (instruction, paramètre); } public <k, v> map <k, v> selectmap (instruction string, string mapkey) {return this.sqlSessionProxy.selectmap (instruction, mapkey); } public <k, v> map <k, v> selectmap (instruction string, paramètre objet, string mapkey) {return this.sqlSessionProxy.selectmap (instruction, paramètre, mapkey); } public <k, v> map <k, v> selectMap (instruction de chaîne, paramètre d'objet, mapkey string, rowbounds rowbounds) {return this.sqlSessionProxy.selectmap (instruction, paramètre, mapkey, rowbounds); } public <e> list <e> selectList (instruction string) {return this.sqlSessionProxy.SelectList (instruction); } public <e> list <e> selectList (instruction string, paramètre objet) {return this.sqlSessionProxy.SelectList (instruction, paramètre); } public <e> list <e> selectList (instruction string, paramètre objet, rowbounds rowbounds) {return this.sqlSessionProxy.SelectList (instruction, paramètre, rowbounds); } public void select (instruction String, Resulthandler Handler) {this.sqlSessionProxy.Select (instruction, gestionnaire); } public void select (instruction de chaîne, paramètre objet, gestionnaire de resulthandler) {this.sqlSessionProxy.Select (instruction, paramètre, gestionnaire); } public void select (instruction String, paramètre d'objet, Rowbounds Rowbounds, Handler Resulthandler) {this.sqlSessionProxy.Select (instruction, paramètre, rowbounds, gestionnaire); } public int insert (instruction String) {return this.sqlSessionProxy.insert (instruction); } public int insert (instruction String, paramètre objet) {return this.sqlSessionProxy.insert (instruction, paramètre); } public int update (instruction String) {return this.sqlSessionProxy.update (instruction); } public int update (instruction String, paramètre objet) {return this.sqlSessionProxy.update (instruction, paramètre); } public int delete (instruction String) {return this.sqlSessionProxy.delete (instruction); } public int delete (instruction String, paramètre objet) {return this.sqlSessionProxy.delete (instruction, paramètre); } public <T> t getMapper (class <t> type) {return this.getConfiguration (). getMapper (type, this); } public void commit () {lancez un nouveau UnsupportedOperationException ("Commit manuel n'est pas autorisé sur un SQLSession géré par le printemps"); } public Void Commit (Boolean Force) {Jetez un nouveau non-soupçon d'obligation ("Commit manuel n'est pas autorisé sur un SQLSession géré par le printemps"); } public void rollback () {lancez un nouveau non soutenu par une conception ("le rollback manuel n'est pas autorisé sur un SQLSession géré par le printemps"); } Public Void Rollback (Boolean Force) {Throw New UnsupportedOperationException ("Rollback manuel n'est pas autorisé sur un SQLSession géré par le printemps"); } public void close () {lancer un nouveau non supporté OperationException ("Manuel Close n'est pas autorisé sur un SQLSession géré par le printemps"); } public void clearCache () {this.sqlSessionProxy.ClearCache (); } Configuration publique getConfiguration () {return this.sqlSessionFactory.getConfiguration (); } Connexion publique getConnection () {return this.sqlSessionProxy.getConnection (); } public list <batchResult> flushstatets () {return this.sqlSessionProxy.flushStAtsations (); } classe privée sqlSessionInterceptor implémente invocationhandler {private sqlSessionInterceptor () {} public objet invoke (proxy objet, méthode de méthode, objet [] args) lance throwable {sqlSession sqlSession = sqlSessionUtils.getsqlsession (sqlSessionTemplate.this.sqlsessionfactory, SQLSessionTemplate.this.sqlsessionfactory, SqlSessionTemplate.this.executOrType, sqlSessionTemplate.this.ExceptionStanslator); Objet déballé; try {object result = méthode.invoke (sqlSession, args); if (! sqlSessionUtils.issqlSessionTransactional (sqlSession, sqlSessionTemplate.This.sqlSessionFactory)) {SqlSession.Commit (true); } non emballé = résultat; } catch (Throwable Var) {Unfapled = exceptionUtil.unwrapthrowable (var); if (sqlSessionTemplate.This.ExceptionStranslator! = null && non emballé Instance de persistance) {SqlSessionUtils.closeSQLSession (sqlSession, SqlSessionTemplate.This.sqlSessionFactory); sqlSession = null; Throwable Translated = SqlSessionTemplate.This.ExceptionStRanslator.TranslateExceptionIfSposible ((persistancexception) Unfallage); if (traduit! = null) {non emballé = traduit; }} Throw (Throwable) Unlemaple; } Enfin {if (sqlSession! = null) {SqlSessionUtils.closeSQLSession (SqlSession, SqlSessionTemplate.This.sqlSessionFactory); }} retour non emballé; }}}}Résumer
Ce qui précède est plusieurs méthodes de configuration pour l'intégration de sources de données de printemps dans MyBatis qui vous a été introduite. J'espère que cela vous sera utile. Si vous avez des questions, laissez-moi un message. L'éditeur vous répondra à temps!