illustrer
Ce projet adopte une structure Maven, qui démontre principalement Spring MVC + MyBatis, contrôleur pour obtenir des données et retourner des données au format JSON.
Structure du projet
Dépendances et instructions du package
Fichier POM:
<project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalation = "http://maven.apache.org/pom/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><Modelversion>4.0.0</Modelversion><groupid>com.hbb0b0.maven01</gro UPID> <ArtifActid> Maven01 </ ArfactId> <Packaging> War </ Packaging> <DERNÉRATEUR> 0.0.1-Snapshot </DERNIFRATION> <NAME> MAVEN01 Maven WebApp </name> <url> http://maven.apache.org </url> <properties> <! - Mybatis version -> <Mybatis.version> 3.2.6 </mybatis.version> <! Version -> <lf4j.version> 1.7.7 </slf4j.version> <log4j.version> 1.2.17 </log4j.version> </properties> <Dedensences> <dependency> <proupId> junit </rom grouped> <Artifactid> JUnit </ artifactid> <verse ion> 3.8.1 </-version> <ccope> Test </cope> </ Dependency> <Dedency> <ProupId> org.springFramework </proupId> <ArtifactId> printemps-webmvc </ artifactid> <version> 4.1.2.release </-version> </Dedency> <! - https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -> <dependency> <proupId> org.codehaus.jackson </proncId> <ArtifActid> Jackson-Mapper-asl </ artifactid> <version> 1.9.2 </DERNIFROITION> https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-core-asl -> <dependency> <proupId> org.codehaus.jackson </proupId> <ArtifActid> Jackson-Core-Asl </ artifactid> <version> 1.9.13 </DERNIFROITION> </DEFENCENCE> https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -> <dependency> <proupId> com.fasterxml.jackson.core </proupId> <Artifactid> Jackson-databind </ artifactid> <version> 2.9.3 </3 -> <dependency> <proupId> org.mybatis </rompupid> <ErtingActid> mybatis-spring </refactId> <version> 1.3.0 </ version> </dependency> <! - Importez MySQL Database Link Jar Package -> <dependency> <GroupId> MySQL </rom grouped> <ArtifActid> MySQL-Connector-Java </Retifactid> <DERNÉE> 5.1.30 </ Version> </Dependency> <! - Mybatis Orm Framework -> <dependency> <proupId> org.mybatis </rompuprid> <letifactive> mybatis </ artifactid> <version> 3.4.1 </-version> </dependency> <petendency> <proupId> org.springframework </pr grouped> <etifactid> printemps-tx </ artifactid> <version> 4.1.2.Releas E </ version> </ Dependency> <Dedency> <ProupId> org.springFramework </proncId> <ArtifActid> printemps-jdbc </ artifactId> <Dersion> 4.1.2.release </ version> </déndency> </peedencies> <fuild> <instalName> Maven01 </inalName> </Duild> </prètement>
Instructions de configuration
web.xml
<! Doctype Web-App Public "- // Sun Microsystems, Inc.//dtd Application Web 2.3 // en" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <splay-name> Archetypey Created Application </ Display-nom Mapping -> <Serplet> <Servlet-Name> Springmvc </vrlett-name> <servlet-Class> org.springFramework.web.servlet.dispatcherservlet </ servlet-Cla-Cla-Cla SS> <IniT-PARAM> <AMAM-NAME> contextConfiglocation </ Param-Name> <AmArd-Value> /Web-inf/Springmvc-servlet.xml </ Param-value> </nitt-Param> <! - <Charot-on-startup> 1 </ Load-on-Startup> -> </ servlet> <servlet-mapping> <servlet-name> springmvc </vrlett-name> <url-potern> / </url-potern> </ servlet-mapping> </ web -pp>
Springmvc-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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4. Package et sous-package -> <contextes: composant-scan basage-package = "com.maven01. *" /> <! - Ne gérez pas la ressource statique -> <mvc: par défaut-service-handler /> <! - Si vous utilisez l'annotation, vous devez configurer le paramètre suivant -> <mvc: annotation-drive /> <! - Dispatcher sevelet -> <MVC: "/ static =". Location = "/ static /" /> <! - Configurez le InternalResourceViewResolver -> <! - Si vous utilisez l'annotation, vous devez configurer le paramètre suivant -> <bean id = "MappingJacksonhttpMessageConverter" class = "org.springframework.http.converter" name = "SupportEdMediaTypes"> <swist> <value> Application / JSON; charset = utf-8 </value> </sist> </ propriété> </-bean> <ean> <eanclass = "org.springframework.web.servlet.view.internalresourceViewResolver" id = "interalresourceViewResolver"> <! Value = "/ Web-Inf / View /" /> <! - Suffix -> <propriété name = "suffix" value = ". jsp" /> </ank> <! - MySql -> <! - Introduire des informations de configuration de source de données externales -> <Eanclass = "org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <woftwames name = "Locations"> <value> CLASSPATH: JDBC.Properties </value> </promest> </ank> <! - Configurez les données de données -> <bean id = "DataSource" class = "org.springframework.jdbc.datasource.DiverManagerDatasource"> <propriété Nom = "DriverClassname" value="${jdbc.driver}"></property><property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.username}"></property><!-- spring and MyBatis are perfectly integrated, and there is no need for mybatis configuration mapping file --><bean id = "sqlSessionFactory"> <propriété name = "dataSource" ref = "dataSource" /> <! - Scan Mapping.xml File -> <propriété Name = "Mappenlocations" Value = "ClassPath: com / maven01 / mapper / *. xml"> </ propriété> </ bean> <! - Le pack -> <an bean> <propriété name = "basepackage" value = "com.maven01.dao" /> <propriété name = "sqlSessionFactoryBeanName" value = "SqlSessionFactory"> </ propriété> </anEn> <! - Configure Transaction Manager -> <Bean id = "txManager" class = "org.springframework.jdbc.datasource.datasourcetransactionManager"> <propriété name = "dataSource" ref = "dataSource"> </ propriété> </ bean> </ beans>jdbc.propertiesjdbc.driver = com.mysql.jdbc.driverjdbc.url = jdbc: mysql: // localhost: 3306 / employés? useucicode = true & worsoncoding = utf-8jdbc.
Configuration du fichier mappeur mybatis
<? xml version = "1.0" Encoding = "UTF-8"?> <! Doctype Mappep Public "- // Mybatis.org//dtd Mappen 3.0 // en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace = "com.maven01.dao.iemployeedao"> <select id = "getAll" resultType = "com.maven01.pojo.employee"> select * NroMloyeesLimit 1,10 </lect> </ mapper>
structure de base de données
Ce projet utilise la base de données des employés de l'exemple de MySQL, et les amis qui en ont besoin peuvent le télécharger eux-mêmes.
http://www3.ntu.edu.sg/home/ehchua/programming/sql/sampledatabases.html
Description du code
modèle
package com.maven01.pojo; employé de classe publique {public int emp_no; public String First_name; public int getEmp_no () {return emp_no;} public void SetEmp_no (int emp_no) {this.emp_no = emp_no;} public string getFirs_name () {return premier) setFirst_name (String first_name) {this.first_name = first_name;}}Dao
package com.maven01.dao; import java.util.list; import org.springframework.sterreotype.repository; import com.maven01.pojo.employee; interface publique iAmployeedao {public list <employee> getall ();};service
package com.maven01.service; import java.util.list; import com.maven01.pojo.employee; interface publique iEmployeService {public list <employee> getall ();}ServiceImpll
package com.maven01.service.impl; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.sterreeotype.service; import com.maven01.dao.iemployee; com.maven01.service. *; import javax.annotation.resource; @ServicePublic class EmployerServiceIMPl implémente iEmployeService {@AutowiredPrivate iPloyageEDAO DAO; Public EmployingServiceImpl () {} public List <Employee> GETALL () {return dao.getall ();}}contrôleur
package com.maven01.controller; import java.util.arraylist; import java.util.list; import javax.annotation.resource; import org.springframework.sterreotype.controller; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestMethod; import org.springframework.web.bind.annotation.responsebody; import com.maven01.dto. *; import com.maven01.pojo.employee; import; com.maven01.service.iemployeeService; @ contrôleur @ requestmapping ("/ mvc") public class Democontroller {@ResourcePrivate iEmployeeService EartherService; @RequestMapping (Method = requestMethod.get, valuey {return EmployingService.getall ();}}Résultats en cours d'exécution
Le code de ce projet a été soumis à Git, et l'adresse de téléchargement est https://github.com/hbb0b0/springmybatis.git
Les pièges rencontrés:
MAPPERScannerConfigurer est configuré pour inclure uniquement la couche DAO. Ne configurez jamais l'intégralité du package à numériser, sinon une erreur se produira: aucun bean de qualification de type [com.maven01.service.iemployeseservice] n'est défini: Bean correspondant unique mais trouvé 2: Employés pourIrniceImpl, iEmployeneService
<! - Spring trouvera automatiquement la classe sous l'interface DAO -> <an Bean> <propriété name = "basepackage" value = "com.maven01. *" /> <Propriété name = "SqlSessionFactoryBeanName" Value = "SqlSessionFactory"> </ Property de type [com.maven01.service.iemployeseservice] est défini: bean assorti unique attendu mais trouvé 2: Employés pourviceImpl, iemployeseserviceat org.springframework.beans.factory.support.defaultListableBeanFactory.DoResolvedependency (defaultListableBeanfactory.java:1061) <! est situé, Spring trouvera automatiquement la classe en dessous -> <an Bean> <propriété name = "basepackage" value = "com.maven01.dao" /> <propriété name = "sqlSessionFactoryBeAnname" value = "sqlSessionFactory"> </ Property> </any>
Notez que la correspondance du package MyBatis est des versions inférieures de Mybatis-Spring et Mybatis et Spring.
java.lang.abstractMethoDerror: org.mybatis.spring.transaction.springManagedTransaction.getTimeout () L
Résumer
Ce qui précède est une explication détaillée de l'exemple de framework MyBatis combiné Spring MVC présenté par l'éditeur. J'espère que cela vous sera utile. Si vous avez des questions, veuillez me laisser un message et l'éditeur vous répondra à temps. Merci beaucoup pour votre soutien au site Web Wulin.com!