Intégration avec Spring3
En tant que cadre de base, le printemps peut intégrer des cadres arrière tels que Hibernate, Mybatis, etc.
L'article précédent présente l'utilisation de Mybatis seul, et la logique générale est:
SQLSessionFactory <- Fichier de configuration (y compris la configuration de la connexion de la base de données)
Ixxxmapper <- sqlSession <- sqlSessionFactory
<- Interface de mappeur <- Mappeur XML
Après avoir obtenu IXXMapper, vous pouvez appeler sa méthode d'interaction des données.
Lors de l'intégration à Spring, les objets ci-dessus doivent être gérés comme des haricots:
DataSource Bean <- Configuration de la connexion de la base de données
SqlSessionFactory Bean <- DataSource
<- Fichier de configuration
UserMapper Bean <- SqlSessionFactory
<- Interface de mappeur
1. Ajouter des dépendances dans pom.xml:
<Properties> <mybatis.spring.version> 1.2.1 </mybatis.spring.version> <dbcp.version> 1.4 </dbcp.version> <printemps.version> 3.1.2.release </sspring.version> </ / Properties> <Dependants> <Dependance> <! - <GroupId> org.mybatis </proupId> <Artifactid> Mybatis-Spring </ Artifactid> <DERVIÈRE> $ {MyBatis.Spring.Version} </DERNIFRIENT> </DENDENCE> <Dendency> <! - Spring Context utilise Spring-jdbc </ GroupId> <ArtefactId> Spring-jdbc </letefactId> <DERSE> $ {printemps.version} </-version> </dependency> <dependency> <! - DataSource est une instance de BasicDataSource -> <ProupId> Commons-Dbcp </proupId> <Artifactid> Commons-dbcp </ptetifActid> <version> </Dependency> <Dedency> <ProupId> org.springFramework </rom grouped> <ArtefactId> printemps-test </refactive> <version> $ {printemps.version} </ version> </pedidency> </Dependces> 2. Créez un fichier beans-da.xml sous le chemin de classe:
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" XSI: ScheMalation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id = "DataSource"> <! value = "com.mysql.jdbc.driver" /> <propriété name = "url" value = "jdbc: mysql: // localhost: 3306 / hbatis? caractères" / fean utf8 "/> <propriété name =" username "value =" root "/> <propriété name =" Passway "value =" 123456 "/> </ bean" id = "SqlSessionFactory"> <! - SqlSessionFactory Bean -> <propriété name = "DataSource" Ref = "DataSource" /> <! - Source de données -> <propriété Name = "Configlocation" Value = "ClassPath: Configuration.xml" /> name = "sqlSessionFactory" ref = "sqlSessionFactory" /> <propriété name = "MAPERInterface" value = "com.john.hbatis.mapper.iusemapper" /> <! - Interface de mappage -> </ beans>
3. Classe de test:
@ContextConfiguration (Locations = {"ClassPath: beans-da.xml"}) public class SpringIntegrationTest étend AbstractTestNgspringContextTests {private static final logger log = loggerFactory.getLogger (SpringIntegrationTest.Class); @Resource Iusemapper Mappeur; @Test public void queryTest () {utilisateur user = mappPer.getUserById (1); log.info ("name: {}, adresse: {}", user.getName (), user.getAddress ()); }} Intégration avec Springmvc
Ici, nous construisons sur l'intégration avec Spring3:
1. Ajouter les dépendances SpringMvc et Freemarker à pom.xml:
<Properties> <freemarker.version> 2.3.19 </freMarker.version> <Servlet.Version> 2.5 </servlet.version> </properties> <dependency> <proupId> org.freMarker </rom grouped> <Artifactid> freemarker </ptetifactid> <version> $ {Freemarker.Version} <dependency> <proupId> javax.servlet </rom grouped> <Artifactid> servlet-api </ artifactId> <DERSE> $ {servlet.version} </ version> <ccope> fourni </cope> </dependency>2. Ajouter l'écoute de Spring et le servlet de Springmvc dans web.xml:
<Dusiner> <auditeur-classe> org.springframework.web.context.contextLoaderListener </ auteur-class> <! - Écoutez les événements de conteneur, initialisez et fermez le contexte de l'application Web et appelez ContextCleanupListener pour nettoyer les ressources -> </ounerner> <outiner> <ouciner-class> org.springframework.web.context.contextCleanupListener </ auteur-class> <! - Nettoyez les ressources destructibles liées à Spring dans ServletContext lorsque l'application Web est fermée -> </ounerner> <Servlet> <Servlet-name> HBATIS </vade-name> <Serplet-Class> org.springframework.web.servlet.dispatcherServlet </vrlett-class> <! - <Init-Param> <Am paramn-Name> ContextConfiglocation </ Param-Name> <Am param-value> /web-inf/hbatis-servlet.xml </ param-value> </web-inf-param> Recherchez $ {project.name} -servlet.xml dans le répertoire Web-Inf -> <ony-on-startup> 1 </ Load-on-Startup> </ Servlet> <Servlet-Mapping> <Servlet-Name> Hbatis </ Servlet-Name> <Url-Pattern> *.3. Créez un nouveau sous Web-Inf:
Fichier de configuration Spring ApplicationContext.xml:
<? xml version = "1.0" Encoding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: p = "http://www.springframework.org/schema/p" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/contex http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd ">; location = "classpath: /database.properties" /> <! - Fichier de configuration de la base de données -> <bean id = "dataSource" p: driverclassname = "$ {driverclassname}" p: url = "$ {url}" p: username = "$ {user_name}" p: mot de passe = "$ {mot de passe}" /> <! id = "sqlSessionFactory"> <! - SQLSessionFactory Object -> <propriété name = "dataSource" ref = "DataSource" /> <! - Data Source -> <propriété name = "configLocation" Value = "ClassPath: Configuration.xml" /> <! - MyBatis Configuration File -> <! - <Propriété Name = "MAPEPER" Value = "ClassPath *: com / John / hbatis / modèle / *. xml" /> -> <! - Vous pouvez configurer le fichier de mappage dans configuration.xml ou ici, mais vous ne pouvez pas avoir Paramettermap, ResultMap, SQL, etc. name = "basepackage" value = "com.john.hbatis.mapper" /> </bEAN> </EANS>database.properties sous le chemin de classe:
DriverClassName = com.mysql.jdbc.driver url = jdbc: mysql: // localhost: 3306 / mybatis? CaractoScoding = utf8 user_name = root mot de passe = 123456
Remarque: Parce que MAPPERScannerConfigurer peut faire en sorte que le nom d'utilisateur récupére le compte de l'utilisateur, ce qui fait échouer la connexion de la base de données, il est donc changé en une autre valeur: user_name.
Fichier de configuration SpringMvc Hbatis-Servlet.xml:
<? xml version = "1.0" encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xsi: schemalation = "http://www.springframework.org/schea/bans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <mvc: annotation-deriven / <! - Requestmappinghandlermapping, requestmappinghandleradapter et exceptionhandlerexceptionResolver pour fournir une prise en charge des annotations telles que @RequestMapping, @ExceptionHandler, etc. -> <context: Component-Scan Base-Package = "Com.john.hbatis.Contrller" /> <! - Scan the Class with Specifiques Annotations Under the Contrôle Voir le processeur -> <bean id = "ViewResolverftl"> <propriété name = "ViewClass" value = "org.springframework.web.servlet.view.freMarker.freMarkerview" /> <propriété Name = "ContentType" value = "text / html; charset = utf-8" /> <propriété = "preFix" value "value =" utf-8 "/> <propriété =" preFix "Value =" Value = "false" /> <propriété name = "ViewNames"> <Array> <Value> *. Ftl </value> </Ray> </ Property> <! - <propriété name = "Suffix" value = ". Ftl" /> -> <propriété Name = "Order" value = "0" /> <! - Priority, plus la valeur, le plus haut de la priorité -> </ bean> name = "TemplateLoaderPaths"> <Sist> <value> / web-inf / ftl / </value> <! - Template Charging Path -> </ist> </ propriété> </ank> </bans>
4. MVC:
Couche de contrôle: userController.java
@Controller @RequestMapping ("/ Article") classe publique UserController {@Autowired Iusemapper Mappeur; @RequestMapping ("/ list") public String showall (ModelMap ModelMap) {list <Article> articles = mappPper.getarticlesByUserId (1); ModelMap.AddAttribute ("Articles", articles); retourner "main.ftl"; }}Voir le calque: main.ftl:
<#List d'articles comme article> <div> $ {article.id}. $ {article.title}: $ {article.content} </div> </ # list>5. Démarrez le projet et entrez le navigateur: http: // localhost: 8080 / hbatis / article / list.htm pour afficher les résultats.