MyBatis est un projet open source d'Apache. En 2010, ce projet a été déplacé de la Fondation du logiciel Apache à Google Code et a été renommé Mybatis.
1. L'ingénierie inverse génère des informations de base
<? xml version = "1.0" Encoding = "utf-8"?> <! doctype générateur ConfigurationPublic "- // Mybatis.org//dtd MyBatis Generator Configuration 1.0 // en "" http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <générateurconfiguration> < Value = "true" /> </ commentgenerator> <! - Informations sur la connexion de la base de données: classe de pilote, adresse de connexion, nom d'utilisateur, mot de passe -> <jdbcconnection driverclass = "com.mysql.jdbc.driver" ConnectionUrl = "jdbc: mysql: // localhost: 3307 / mybatis" userid = "root" mot de passe = "jalja"> </ jdbcconnection> <! - Par défaut Faux, analyser les types décimaux et numériques JDBC en entier, et lorsque le type décimal et numérique JDBC résolve à java.math.bigdecimal -> <javatyperesolver> /> </ javatyperesolver> <! - TargetProject: Emplacement de la classe PO générée -> <javamodelgenerator targetpackage = "com.jalja.springmvc_mybatis.model.pojo" cibleProject = "./ Src"> <! name = "ActiveBpackages" value = "false" /> <! - Les espaces avant et après la valeur renvoyée de la base de données sont nettoyées -> <propriété name = "trimStrings" value = "true" /> </ javamodelGenerator> <! - TargetProject: où le fichier de cartes de mappeur est généré -> <sqlMapGenerator TargetPackage = "com.jalja.springmvc_mybatis.mapper" TargetProject = "./ Src"> <! - AutantUbPackages: Que ce soit le schéma être le suffixe du package -> <propriété Name = "ActiveBpackages" Value = "false" /> </ / sqlmapGenerator> <! -> <propriété name = "ActiveBpackages" value = "false" /> </ sqlmapGenerator> <! - TargetPackage: Emplacement de la génération d'interface de mappe ActiveBpackages: Que le schéma soit le suffixe du package -> <propriété name = "ActiveBpackages" value = "false" /> </ javaclientGenerator> <! - Spécifiez les tables de base de données -> <table tableName = "items"> </ table> <table de table de databe = "Tablet"> </ table TableName = "User"> </ Table> </ context> </neneratorConfiguration> public static void main (String [] arhs) lève une exception {list <string> warnings = new ArrayList <string> (); booléen sumpacre = true; file configFile = new File ("src.main.resources / generator.xml"); configurationParser cp = new ConfigurationPaSer (avertissements); configuration config = cp.parsEconfiguration (configFile); defaultShellCallback callback = new defaultShellCallback (écrasant); MyBatiSgenerator MyBatisGenerator = new MybatisGenerator (config, callback, warning 2. Springmvc et Mybatis intègrent divers fichiers de configuration
1. Structure du projet
2. Le code central de chaque fichier
A.web.xml
<? xml version = "1.0" Encoding = "UTF-8"?> <Web-App xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: Schemalocation = "http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" Version = "3.0"> <Welcome-File-List> <Deen welcome-File> index.jsp </ bienvenue-file> </ welcome-file-list> <ptext-param> <param-name> contextConfiglocation </ param-name> <param-value> classpath: spring / applicationContext - *. xml </ param-valent> </featter-param> <fouger> <ouciner-Class> org.springframework.web.context.contextLoaderListener </ auteur-class> </duner> <ftext-Param> <Am param-name> log4jconfiglocation </ param-name> <am-value> classpath: log4j.properties </ param-value> </ context-patam> <pext-paam> <param-name> log4jrefreshinterval </ param-name> <param-valeur> 3000 </ param-valeur> </ context-param> <ouciner> <auditeur-class> org.springframework.web.util.log4jconfigListener </ auteur-class> </duner> <! - Post Demande Code -> <filter> <Filter-Name> SpringEncodingFilter </ Filter-Name> <Lilter-Class> org.springFramework.web.filter.CharacTerencodingFilter </ Filter-Class> <Init-Param> <Am paramage> Encoding </Am paramter> <Am-Value> UTF-8 </AMAD -VALUE> </1nit-Param> <Init-Param> <Am param-name> Forceencoding </ param-name> <param-value> true </ param-value> </nitt-Param> </filter> <filter-mapping> <filter-name> SpringencodingFilter </filter-name> <Url-Pattern> *. Contrôleur -> <Serplet> <Servlet-Name> Springmvc </vrlett-name> <Servlet-Class> org.springframework.web.servlet.dispatcherservlet </ servlet-Class> <Init-Param> <! - ContextConfiglocation charge name-servlet.xml (springmvc-servlet.xml) -> <param-name> contextConfiglocation </ param-name> <param-value> classpath: spring / springmvc.xml </onsam-value> </itit-param> <foard-startup> 1 </sard-startup> </ serplet> <servlet-mapping> <Servlet-Name> Springmvc </vrlet-name> <! - 1, * .do: Dispatcherservlet analyse tous les accès se terminant par * .do2. /: Dispatterservlet analyse toutes les demandes (y compris les ressources statiques) Cette configuration peut implémenter URL3 de style repos, / *: Cette configuration sera finalement transmise à une page JSP -> <Url-Pattern> *. Do </rl-potern> </ serplet-mapping> <! <Servlet-Class> org.springframework.web.servlet.dispatcherservlet </vrlet-Class> <Init-Param> <Am param-Name> ContextConFiglocation </ Param-Name> <AmArd-Value> ClassPath: Spring / applicationContext-Springmvc.xml </ param-Value> </IniT-Param> </ servlet> <servlet-mapping> <servlet-name> springmvc_rest </vrlett-name> <url-potern> / </url-potern> </ servlet-mapping> -> <ession-config> <session-timeout> 30 </ession-timeout> </ session-config> </wek-apprent>
né config / mybatis / applicationContext-mybatis.xml
<? xml version = "1.0" Encoding = "utf-8"?> <! Doctype Configuration public "- // mybatis.org//dtd config 3.0 // en" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <! Les paramètres d'exécution peuvent être ajustés lorsque MyBatis s'exécute, tel que: Activer le cache secondaire, activer les typealias de chargement retardé (Type Alias): Définissez le type de paramètre de paramètre de paramètre dans MAPPER.XML Lorsque vous renvoyez un type, vous devez spécifier le chemin du type et il n'est pas pratique à développer. Nous spécifierons l'alias pour ces types. TypeHandler: Dans MyBatis, la conversion du type JDBC et du type Java est terminée via TypeHandler. Le processeur fourni par MyBatis peut répondre aux exigences de développement ObjectFactory: Plugins: Environments (Environments Collection Attribut Object): Environment (Environment Substribut Object): TransactionManager (Management des transactions): DataSource (source de données): Mappers (Mapper): -> <paramètres> <! name = "lazyloadingEnabled" value = "true" /> <! - Chargement actif vers le chargement passif -> <setting name = "AggressIlayloading" value = "false" /> <! - Activer level 2 cache -> <paraming name = "cacheenabled" value = "true" /> </ settings> <typealiases> <! - Définition pour les allias seuls -> <! Type = "com.jalja.mybatis.model.user" alias = "user" /> -> <! - Définition de l'alias par lots Mybatis Le nom de classe dans le package de numérisation automatique est le nom de classe (les deux premières lettres peuvent être utilisées pour la partie supérieure et la cote) -> <package name = "com.jalja.springmvc_mybatis.modmel.pojo" name = "com.jalja.springmvc_mybatis.model.custom" /> <package name = "com.jalja.springmvc_mybatis.model.vo" /> </copaliases> <! - ressource = "com / jalja / printemps_mybatis / mapper / userMapper.xml" /> -> <! - Après avoir intégré à Spring, vous pouvez supprimer <package name = "com.jalja.spring_mybatis.mapper" /> </mappers> -> </ configuration>
c. config / printemps / applicationContext-dao.xml
<? xml version = "1.0" Encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.spring xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://www.springframeworkworkwork http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-Beans-..2.xsdd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"><! name = "Locations"> <sist> <value> classPath: Resources / config / jdbc.properties </value> </sist> </ propriété> </ bean> -> <bean id = "dataSource" destrement-méthod = "close"> <propriété name = "DriverClassName"> <value> $ {jdbc_driverclassname} </value> </ property> name = "url"> <value> $ {jdbc_url} </value> </ propriété> <propriété name = "username"> <value> $ {jdbc_username} </value> </ propriété> <propriété name = "mot de passe"> <! name = "maxactive"> <value> 20 </value> </ propriété> <! - Initialisez la taille de la connexion -> <propriété name = "initialSize"> <value> 1 </value> </ propriété> <! - Obtenez le temps d'attente maximal pour la connexion -> <propriété name = "Maxwait"> <value> 60000 </value> </prewet> <! - Maximum Idle Connection Pool -> <prewet name = "maxidle"> <value> 20 </value> </ propriété> <! - Pool de connexion inactif minimum -> <propriété name = "minidle"> <value> 3 </value> </ propriété> <! - Connexion inutile -> propriété Name = "RemoveAbandonEd"> <value> true </value> </ / propriété <! - Clear Time for Usless Connection -> <prewet> </ Value> </ propriété> <! - Effacer le temps d'attente pour la connexion sans usages -> <value> True </value> </ Property <! name = "RemoveAbandOnEdTimeout"> <value> 180 </value> </ propriété> <! - Propriétés de connexion -> <propriété name = "ConnectionProperties"> <Value> ClientEncoding = UTF-8 </ Value> </ Property> </ Bean> <! - Intégration parfaite de Spring et Mybatis -> <Bean Id = "SQLSessionFactory"> <propriété = "Dataource" ref = "dataSource" /> <propriété name = "configLocation" value = "classpath: mybatis / applicationContext-mybatis.xml" /> </ank> <! - Mappen Scanner -> <anEn> <! - Analyse le chemin du package Si vous avez besoin de numériser plusieurs packages " Value = "com.jalja.springmvc_mybatis.mapper" /> <propriété name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" /> </ank> <! - Management de transaction déclarative Management transaction Ref = "DataSource"> </ propriété> </ bean> <! - Configuration de la notification des transactions -> <tx: conseil id = "txadvice" transaction-manager = "transactionManager"> <tx: attributes> <tx: méthode name = "update *" propagation = "requis" /> <tx: méthode = "SAVE *" propagation = "requise" /> <tx: "de la méthode * propagation = "requise" /> <tx: méthode name = "get *" propagation = "supports" read-only = "true" /> <tx: méthode name = "find *" propagation = "supports" readly = "true" /> <tx: attributes> </ tx: conseils> <! - Configurer la transaction ponctuelle et ne pas associer à la transaction-insisert-insert-insert avec les attributions de transaction aop -> <aop: config> <aop: conseiller conseils-ref = "txadvice" Pointcut = "Exécution (* com.jalja.springmvc_mybatis.service.impl. d.config / printemps / applicationcontext-service.xml
<? xml version = "1.0" Encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.spring xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://www.springframeworkworkwork http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-Beans-..2.xsdd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd pour id = "itemsService"> </bEAN> </EANS>
E, config / printemps / springmvc.xml
<? xml version = "1.0" Encoding = "utf-8"?> <beans xmlns = "http://www.springframework.org/schema/beans" xmlns: aop = "http://www.springframework.org/schema/aop" xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.spring xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation = "http://www.springframeworkworkwork http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-Beans-3.0.xsde http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3..2.xsdâtâché Mappeur -> <! - Mapper org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping springmvc3.1 -> <! - Mappen org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping springmvc3.1 -> <! - MAVERAT. org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping springmvc3.1 After -> <! - adapter org.springframework.web.servlet.mvc.annotation.annotationMethodLeradapter avant Springmvc.1 -> <! org.springframework.web.servlet.mvc.method.annotation.requestmappingHandlerAdapter après Springmvc3.1 -> <! - Configurez le mappeur et l'adaptateur <anan /> <ance /> -> <! - Allumez le mappeur et l'adaptateur d'annotation. Cette méthode charge de nombreuses méthodes de liaison des paramètres par défaut, telles que JSON Conversion Parser -> <MVC: Annotation-Driven /> <! - Configurer Handler <Eban /> -> <! - La configuration de l'annotation est basée sur la méthode de la construction de la numérisation -> <Context: Component-Scan Base-Package = "Com.jalja. Parser -> <MVC: ANNOTATION-ADING CONVERSION-SERVICE = "ConversionService" /> <Bean Id = "ConversionService"> <propriété name = "Converters"> <sist> <! - Date Type Conversion -> <ean> </Ean> </ist> </ propriété> </ Bean> <! - Prise en charge des exceptions mondiales -> <ean /> <! - Fichier Upload -> <! id = "MultipartResolver"> <! - Taille de fichier 5m -> <propriété name = "MaxuploadSize" value = "5242880" /> </ bean> <! - Problème d'accès aux ressources statique causée par la programmation à l'aide de style restul -> <! -> <mvc: intercepteurs> <mvc: interceptor> <mvc: mapping path = "/ **" /> <bean /> </ mvc: interceptor> </ mvc: interceptors> <! - Voir la carte jsp analyse jstl -> <an bean> <! value = "org.springframework.web.servlet.view.jstlview" /> <propriété name = "prefix" value = "/ web-inf / jsp /" /> <propriété name = "suffix" value = ". jsp" /> </ bean> </ beeps>
f, config / jdbc.properties
jdbc_driverclassname = com.mysql.jdbc.driverjdbc_url = jdbc: mysql: // localhost: 3306 / mybatis? useucicode = true & worseccoding = utf-8jdbc_username = rootjdbc_password = 111111
G, config / log4j.properties
# Dans l'environnement de développement, le niveau de journal doit être défini sur le débogage, l'environnement de génération doit être défini sur info ou errorlog4j.rootlogger = debug, stdoutlog4j.logger.org.apache.ibatis = debuglog4j.appendender.stdout = org.apache.log4j.consoleAppenderLog4j.appendender.stdout.layout = org.apache.log4j.patternlayoutlog4j.apprender.stdout.layout.conversionpattern =% 5p
H, com / jalja / springmvc_mybatis / contrôleur / itemscontroller.java
package com.jalja.springmvc_mybatis.Controller; import java.io.file; import java.util.list; import java.util.uuid; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.Contrôler; org.springframework.ui.model; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping; org.springframework.web.bind.annotation.requestMethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.Responsebody; com.jalja.springmvc_mybatis.exception.customexception; import com.jalja.springmvc_mybatis.model.custom.itemsomystom; import com.jalja.springmvc_mybatis.service.itemsservice; / *** product * @author pc003 * conterver converter converter; / *** product * @author pc003 * conterver converter converter; / *** product * @author pc003 * Conterver Converter Converre Springmvc fournit de nombreux convertisseurs de paramètres * / @ contrôleur @ requestmapping ("/ items") // mappage de requête étroite Mapping public class itemsController {@autowired itelesService itemsService; @Requestmapping (value = "/ finitmusth") public string finittemsList (modèle modèle) lance exception {list <itemSustom> itementsList = itementsService.FinDitemsList (null); System.out.println (itemsList); Model.Addattribute ("ItemsList", itemsList); return "itemsList";} @ requestmapping (value = "/ editItems", méthode = {requestMethod.post, requestMethod.get}) // Limiter la méthode de requête HTTP Paramètres formels requis: Spécifiez que la valeur de l'attribut doit être transmise dans DefaultValue: Définissez la valeur par défaut Public String EditItems (modèle modèle, @RequestParam (valeur = "id", obligatoire = true, defaultValue = "0") IntegerId) lance une exception {itemSCustomysCustom = null) Customexception ("Product n'existe pas");} modèle.addAttribute ("itemsCustom", itemsCustom); return "editItems";} @ requestmapping (value = "/ updateItems") String public editItemsSubmit (String Iteger, itelescustomscustam, multipartFile itemSpic) exception {String uploadFileName = itemspic.getoriginalFileName (); // Obtenez le nom de fichier téléchargé if (itemspic! = null && uploadFileName! = null &&! uploadFileName.equals ("")) {String imagesPath = "e: // développe // upload // images //"; String newFileName = uUid.randomuUid () + uploadFileName.Substring (uploadFileName.LastIndexof ("."), uploadFileName.length ()); file newFile = new File (imagesPath + NewFilename); itemspic.transferto (newfile); // écrire des données dans le mémoire à Disk to Disk itemsCustom.setpic (newFileName);} itemsService.updateItemsById (id, itemsCustom); return "redirect: finDitemsList.do"; // rediriger} // Utilisation de JSON @ResponseBody: To Office to JSON output @RequestBody: Pour demander des paramètres à Java Object @RequestMapping (Value = "/ JSonRequest") public @ResponseBody itemsCustom JSONQuest (@requestbody itemscustCustom) lance exception {returnCustom;} // Retfulbody Style Programmation / RestfulRequest / {id}: Cela signifie passer le paramètre à cette position au nom spécifié par @PathVariable @RequestMapping (value = "/ restfulEquest / {id}") public @ResponseBody itemsCustom restfulRequest (@pathvariable ("id") Id id) throws exception { itemsCustom = itementsService.FinDitemsById (id); return itemscustom;}}Ce qui précède est le code d'exemple MyBatis intégré SpringMVC vous présenté par l'éditeur. J'espère que cela vous sera utile. Si vous souhaitez en savoir plus d'informations, veuillez faire attention au site Web Wulin.com!