MyBatis ist ein Open -Source -Projekt von Apache. Im Jahr 2010 wurde dieses Projekt von der Apache Software Foundation in Google Code verschoben und in MyBatis umbenannt.
1. Reverse Engineering generiert grundlegende Informationen
<? 1.0 // en "" http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id =" testtables "targetruntime =" mybatis3 "> <commentgenerator> <! NAME = "SuppressAllComentments" Value = "True"/> </commentgenerator> <!-Datenbankverbindungsinformationen: Treiberklasse, Verbindungsadresse, Benutzername, Passwort-> <Jdbcconnection DriverClass = "com.mysql.jdbc.driver" Connectionurl = "jdbc: mysql: ///. localHost: 3307/mybatis" " userID = "root" password = "jalja"> </jdbcconnection> <!-Standard Falsch, analysieren Sie die jdbc-Dezimal- und numerischen Typen in Ganzzahl, und wenn wahr ist, entschließt JDBC Decimal und Numeric Type to java.math.bigDecimal-> <javatyperesolver> <Seigenschaftsname = "courndecimal-y. Javatyperesolver> <immobilien name /> </javatyperesolver> <!-targetProject: Ort der generierten PO-Klasse-> <JavamodelGenerator targetPackage = "com.jalja.springMvc_mybatis.model.pojo" targetProject = ". NAME = "AktiviertUbpackages" value = "false" /> <!-Die Leerzeichen vor und nach dem von der Datenbank zurückgegebenen Wert sind gereinigt-> <Eigenschaft name = "trimstrings" value = "true" /> < /javamodelGenerator> <!-targetProject: wobei die Mapper-Kartendatei-> < targetPackage = "com.jalja.springmvc_mybatis.mapper" targetProject = "./ Src"> <!-Aktiviert Abpackages: Ob das Schema das Suffix des Pakets ist-> <Eigenschaft name = "EngsSubpackages" value = "false"/> </SQLMAPGENSURTE> </SQLMAPGENERS> </> </SQLMAPGENERS> <! Paket-> <Eigenschaft name = "enableSubpackages" value = "false"/> </sqlmapgenerator> <!-targetPackage: Ort der Mapper-Schnittstelle-> <JavaClientGenerator Typ = "xmlmapper" targetPackage = "com.jalja.sspringmvc_mybatis.maper". enableSubPackages: Whether to let schema be the suffix of the package --><property name="enableSubPackages" value="false" /></javaClientGenerator><!-- Specify database tables--><table tableName="items"></table><table tableName="orders"></table><table tableName="orderdetail"></table><table tableName = "user"> </table> </context> </generatorConfiguration> public static void main (String [] arhs) löst Ausnahme aus {list <string> warnings = new ArrayList <string> (); boolean overwrite = true; Dateikonfiguration = new File ("src.resources.xm.xml"). ConfigurationParser (Warnings); configuration config = cp.ParseConfiguration (configFile); defaultShellCallback callback = new defaultShellCallback (Überschreiber); MyBatisGenerator myBatisgenerator = new mybatisgenerator (config, callback, Warnungen); 2. SpringMVC und MyBatis integrieren verschiedene Konfigurationsdateien
1. Projektstruktur
2. Der Kerncode jeder Datei
A.Web.xml
<xml Version = "1.0" coding = "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/javaeHttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" Version = "3.0"> <Welcome-File-List> <Welcome-File> Index.jsp </Welcome-File> </Welcome-File-List> <Context-Param> <Param-name> contextconfigLocation </param-name> <param-value> classpath: Spring/ApplicationContext-*. <Hörer-Class> org.springFramework.web.context.contextloaderListener </Listener-Klasse> </Listener> <context-Param> <PARAM-NAME> LOG4JCONFILOCATION </param-name> <param-value> classpath: log4j.properties </param-value> <Param-name> log4jreFreshInterval </param-name> <param-value> 3000 </param-value> </context-param> <hörer> <hörerklasse> org.springframework.web.util.log4jconfigListener </Hörer-Class> </Listener> <!-Garbled-Anfrages Garbled-Anfragen </Hörer-Class> </hörer> <!-<!-<! CODE-> <Filter> <Filter-Name> SpringCodingFilter </Filter-Name> <Filter-Class> org.springFramework.Web.Filter.Charactercodingfilter </filter-class> <init-param> </param-value> </init-param> <init-param> <param-name> comparityCoding </param-name> <param-value> true </param-value> </init-param> </filter> <filter-mapping> <Filter-name> FPINGENCODINGFILTER </filter-name> </url-patter>* Front-End-Controller-> <servlet> <Servlet-name> SpringMvc </servlet-name> <Servlet-Klasse> org.springFramework.web.servlet.DispatcherServlet </Servlet-Class> <init-param> <!-ContextConfigLocation Lades SpringMvc-Ladedatei (Prozessor Adapter), MapPer-Lade-Ladedateien, die Konfigurationsdatei des Prozessors (Prozessor Adapter), MapPer-Lade-Ladedatei, Makcode, MapPer) Wenn nicht konfiguriert, ist die Datei des Prozessors (Prozessor Adapter), MapPer-Ladungen, nicht konfiguriert, MapPer), wenn nicht konfiguriert ist, ist der Prozessor-Adapter, MapPer), wenn nicht konfiguriert ist, der Prozessor, der Prozessor, der Prozessor, der Prozessor, der Prozessor, der Prozessor-Adapter), wenn nicht /WEB-INF/servlet name-servlet.xml(springMvc-servlet.xml)--><param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-mapping> <servlet-name> SpringMVC </Servlet-name> <!-1, *.do: Dispatherservlet analysiert alle Zugriffe, die in *.do2 enden. / :DispatcherServlet parses all requests (including static resources) This configuration can implement restful-style url3, /*: This configuration will eventually be forwarded to a jsp page--><url-pattern>*.do</url-pattern> </servlet-mapping> <!-- springMvc front-end controller RestFul <servlet> <servlet-name>springMvc_rest</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <Servlet-Mapping> <Servlet-name> SpringMVC_REST </Servlet-Name> <URL-PATTERN>/</URL-PATTERN> </Servlet-Mapping>-> <Sesion-config> <Session-Timeout> 30 </Session-Timeout> </session-conFig> </web-Apps> </web-Apps> </web-applyout>
B. config/mybatis/applicationContext-mybatis.xml
<? Ausführende Parameter können angepasst werden, wenn MyBatis ausgeführt wird, z. B.: Aktivieren von Sekundärcache, verzögerte Lade -Typias (Typ Alias) aktivieren: Definieren Sie den Parameter -Parameter -Typ -Ergebnistyp in Mapper.xml Bei Rückgabe eines Typs müssen Sie den Pfad des Typs spezifizieren und sich nicht entwickeln. Wir werden den Alias für diese Typen angeben. TypeHandler: In MyBatis wird die Konvertierung des JDBC -Typs und des Java -Typs über TypHandler abgeschlossen. Der von MyBatis bereitgestellte Prozessor kann die Entwicklungsanforderungen erfüllen. name = "LazyLoadingInabled" value = "true"/> <!-aktives Laden zum passiven Laden-> <Einstellungsname = "AggressingAnyLoading" value = "false"/> <!-Level 2 cache-> <Einstellung Name = "Cacheenabled" value = "true"/> </</</<Typisalias> <! Type = "com.jalja.mybatis.model.user" alias = "user"/>-> <!-Definition von Batch alias mybatis Der Klassenname im automatischen Scanning-Paket ist der Klassenname (beide Erstbriefe können für obere und untere Fall verwendet werden)-> <package name = "com.ja.spingmvc_mybatis.model.poja.springmvc_mybatis.model.poja.springmvc_mybatis.model name="com.jalja.springmvc_mybatis.model.custom"/><package name="com.jalja.springmvc_mybatis.model.vo"/></typeAliases><!--Load the mapping file--><!-- <mappers> <mapper ressourcen = "com/jalja/spring_mybatis/mapper/usermapper.xml"/>-> <!
C. config/fing/applicationContext-dao.xml
<? xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://wwwwwwwwwwwwwww./Mwww. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframe.org/schema/beans/spans/span- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.spingframework.org/sschema/mvc http://www.springframework.org/schema/mvc/spring-mvc-32.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"><!-Einführung von JDBC-Konfigurationsdatei-> <context: Property-Placeholder locum = "classPath: jdbc.properties"/> <!-JDBC-Konfiguration <Bean id = "Immobilien"> <!-JDBC-Konfiguration <Bean id = "immobilien"> <!-JDBC-Konfiguration <Bean id = "Immobilien"> <- name = "standplätze"> <list> <wert> classPath: Ressourcen/config/jdbc.properties </value> </list> </property> </bean>-> <bean id = "dataSource" Destroy-Method = "CLIDE"> <Property name = "DriseClassname"> <Vote> $ {JDBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DBC_DB. name = "url"> <value> $ {jdbc_url} </value> </property> <Eigenschaft name = "userername"> <value> $ {jdbc_username} </value> </Eigenschaft> <Eigenschaft name = "Passwort"> <value> {value-Pool-Maximum {maximum}} </value> </ubeigen> </ubmobilien </</</</</</</</</</</</</</</</</</</</</</</</</</</<! name = "maxActive"> <wert> 20 </value> </property> <!-Initialisieren Sie die Verbindungsgröße-> <Eigenschaft name = "initialSize"> <value> 1 </value> </property> <!-Erhalten Sie die maximale Wartezeit für die Verbindung-> <Eigenschaft Name = "Maxwait"> <value> 60000 </value> </value> </probium> </probium> </machung> <! name = "maxidle"> <value> 20 </value> </property> <!-minimaler Leerlaufverbindungspool-> <Eigenschaft name = "minidle"> <value> 3 </value> </property> <!-Automatisch löschen nutzloser Verbindung-> <Eigenschaft name = "RemoveAntoned"> <value> true </value> </achapien </</</</</</</</</</</</</</</</</</<! name = "removeAsBandOnedTimeout"> <wert> 180 </value> </property> <!-Verbindungseigenschaften-> <Eigenschaft name = "ConnectionProperties"> <wert> ClientCoding = Utf-8 </value> </Property> </bean> <!-Perfect Integration von Spring und MyBatis-> <bean id = " ref = "dataSource"/> <Eigenschaft name = "configLocation" value = "classPath: mybatis/applicationContext-mybatis.xml"/> </bean> <!-Mapper Scanner-> <bean> <!-scannen Sie den Paketpfad, wenn Sie mehrere Pakete scannen müssen, eine halbe Width-Komma, um sie zu trennen. value = "com.jalja.springmvc_mybatis.mapper"/> <Eigenschaft name = "sqlSessionFactoryBeanname" value = " ref = "dataSource"> </property> </bean> <!-Transaktionsbenachrichtigung konfigurieren-> <tx: rating id = "txadvice" transaction-Manager = "TransactionManager"> <tx: Attribute> <tx: method name = "update*" Propagation = "Erforderlich"/> <Tx: Methode name = "savagation Propagation = "Erforderlich"/> <tx: method name = "get*" propagation = "unterstützt" schreibgeschützt = "true"/> <tx: method name = "find*" propagation = "unterstützt" -Re-Nur-Nur-Only = "True"/> <tx: Attribute> </tx: Ratschläge> <! -> <AOP: config> <AOP: Advisor Ratschläge-ref = "txadvice" pointCut = "Execution (*com.jalja.springMvc_mybatis.service.impl.*. D.Config/Spring/ApplicationContext-Service.xml
<? xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://wwwwwwwwwwwwwww./Mwww. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springframe.org/schema/beans/spans/span- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.spingframework.org/sschema/mvc http://www.springframework.org/schema/mvc/spring-mvc-32.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.xsdhttp://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/sping-cache/sping-cache- id = "itemsService"> </bean> </beans>
e, config/fRING/SPRINGMVC.XML
<? xmlns: cache = "http://www.springframework.org/schema/cache" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://wwwwwwwwwwwwwww./Mwww. xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance" xsi: schemalocation http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframe.org/schema/beans http://www.springframe.org/schema/beans/beans/beans/beans/span- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/sschema/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.g/schema Mapper-> <!-Mapper org.springframework.web.servlet.mvc.annotation.DefaultAntationHandlermaping SpringMvc3.1-> <!-Mapper org.springframework.web.Servlet.Mvc.Annotation.DefaultAnnotation-Spring-Handlungs-SpringMvcing org.springframework.web.servlet.mvc.method.annotation.RequestMapingHandlermaping SpringMvc3.1 Nach-> <!-adapter org.spingframework.web.Servlet.Mvc.Annotation.AnnotationMethod und vor SpringMvc3.1-> org.springFramework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter nach SpringMvc3.1-> <!-Konfigurieren Sie Mapper und Adapter <bean/> <bean/>-> <!-Schalten Sie den Annotation Mapper und Adapter ein. Diese Methode lädt viele Parameterbindungsmethoden standardmäßig, z. Parameter Parser-> <mvc: Annotationsbetriebene Conversion-service = "ConversionService"/> <bean id = "ConversionService"> <Eigenschaft name = "konverters"> <list> <!-Datumstyp Conversion-> <Bean> </bean> </list> </property> </ban <!-Global AUSBAGE FOOD FÜR FÜR FÜR FÜHRUNG FÜR FÜHRUNG FÜR FÜHRUNG FÜR FÜHRUNG FÜR FÜHRUNG FÜR FÜR FÜHRUNG FÜR FÜR FÜHRUNG FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR FÜR DIE. -> <bean id = "multipartresolver"> <!-Dateigröße 5M-> <Eigenschaft name = "maxUploadsize" value = "5242880"/> </bean> <!-statische Ressourcenzugriffsprobleme, die durch Programmierung mit RESTFUR-Stil verursacht wurden-<! Interceptor-Konfiguration-> <MVC: Interceptors> <mvc: interceptor> <mvc: maping path = "/**"/> <bean/> </mvc: interceptor> </mvc: interceptors> <!-Map-JSP-Parsing verwendet JSTL-> <bean> <!-Defaults-Benutzern. value = "org.springframework.web.servlet.view.jstlview"/> <Eigenschaft name = "prefix" value = "/web-inf/jsp/"/> <Eigenschaft name = "suffix" value = ". jsp"/> </bean> </beans>
F, config/jdbc.properties
JDBC_DRIVERCLASSNAME = com.mysql.jdbc.driverjdbc_url = jdbc: mysql: // localhost: 3306/mybatis? useUnicode = true & charakteristischesCoding = utf-8jdbc_username = rootjdbc_password = 111111
G, config/log4j.properties
#In der Entwicklungsumgebung sollte die Protokollebene auf Debug eingestellt werden. Die Generationsumgebung sollte auf Info oder FehlerLog4j.Rootlogger = Debug, eingestellt werden. stdoutlog4j.logger.org.apache.ibatis=debuglog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m %n
h, com/jalja/springmvc_mybatis/controller/itemsController.java
Paket com.jalja.springmvc_mybatis.controller; import java.io.file; import Java.util.list; import Java.util.uuid; org.springframework.ui.model; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation organ. com.jalja.springmvc_mybatis.exception.customexception; import com.jalja.springMvc_mybatis.model.custom.itemscustom; SpringMVC liefert viele Parameterkonverter*/@Controller@requestmapping ("/items") // enge Request -Mapping public class itemsController {@autowired itemService itemsService; @RequestMapping (value = "/findItemSlist") öffentliche Zeichenfolge FindEsList (Modell) Ausnahme {list <itemsCustom> itemsList = itemsService.finditemSlist (null); system.out.println (itemsList); model.addAttribute ("itemsList", itemsList); return "itemsList";}@requestmapping (value = "/edititems", methode = {requestMethod.post.postmaping. Vorgeschriebene Parameter: Geben Sie an, dass der Wert des Attributs in defaultValue übergeben werden muss: Setzen Sie den Standardwert öffentliche String -EditiTEMs (Modellmodell, @RequestParam (value = "id", fordert = true, defaultValue = "0") Integer itemsidsid) aus der Ausnahme {itemsCustom itemsCustom = itemService. CustomException ("Produkt existiert nicht");} model.addAttribute ("itemsCustom", itemsCustom); return "edititem UploadFileName = itemsspic.getoriginalFileName (); // Erhalten Sie den Dateinamen hochgeladen (itemsspic! = null && uploadFileName! newFileName=UUID.randomUUID()+uploadFileName.substring(uploadFileName.lastIndexOf("."),uploadFileName.length());File newFile=new File(imagesPath+newFileName);itemsPic.transferTo(newFile);//Write data in memory to disk itemsCustom.setpic (newFileName);} itemsService.updateemsById (ID, itemsCustom); return "Redirect: findItemSlist.do"; // redirect} // Verwendung von JSON @ResponseBody: Einwände gegen JSON Output @RequestBody: Anfordern von Parametern an Java -Objekt @RequestMapping (value = "/JsonRequest") public @RespondeBody Programmierung/restfulRequest/{id}: Es bedeutet, den Parameter an dieser Position an den von @PathVariable @RequestMapping (value = "/restfulRequest/{id}") public @responbody itemscustom restfulRequest ( @pathVarable ("id" id "id") intiere id {idsger id {id ") zu übergebene Parameter. itemsCustom = itemsService.finditemsById (id); return itemsCustom;}}Das obige ist der von dem Editor vorgestellte SpringMVC -Integrated MyBatis -Beispielcode. Ich hoffe, es wird Ihnen hilfreich sein. Wenn Sie weitere Informationen wissen möchten, achten Sie bitte auf die Website wulin.com!