MyBatis es un proyecto de código abierto de Apache. En 2010, este proyecto se trasladó de Apache Software Foundation a Google Code y pasó a llamarse MyBatis.
1. Ingeniería inversa genera información básica
<? xml versión = "1.0" encoding = "utf-8"?> <! Doctype GeneratorConfigurationPublic "-// mybatis.org//dtd Configuración del generador de mybatis 1.0 // en "" http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd "> <generatorConfiguration> <context id =" testtable "targetRuntime =" mybatis3 "> <commentGenerator> <!-si elimina los comentarios de la propiedad automática verdadera: no: no: no-" myBatis3 "> <CommentGenerator> <!---si elimina los comentarios de la propiedad automática verdadera: no: no: no-n. value = "true"/> </commentGenerator> <!-Información de conexión de la base de datos: clase de controlador, dirección de conexión, nombre de usuario, contraseña-> <jdbcconnection conductClass = "com.mysql.jdbc.driver" ConnectionUrl = "jdbc: mysql: // localhost: 3307/mybatis" userId = "root" contraseña = "jalja"> </jdbcconnection> <!-predeterminado falso, analizar los tipos JDBC decimal y numéricos en entero, y cuando es verdadero, jdbc decimal y tipo numérico resueltos a java.math.bigdecimal-> <javatyPeresolver> <name de la propiedad = "ForceBigDecimals" Valor "valor" valor "valor" valor "value" "value" "value" valores "" value "" value "" " /> </javatyPeresolver> <!-TargetProject: Ubicación de la clase PO generada-> <javaModelGenerator TargetPackage = "com.jalja.springmvc_mybatis.model.pojo" TargetProject = "./ src"> <!-Enblesubackage name = "habilsubpackages" value = "false" /> <!-Los espacios antes y después del valor devuelto de la base de datos se limpian-> <name de propiedad = "TrimStrings" value = "true" /> < /javaModelGenerator> <!-TargetProject: donde el archivo de mapa mapper se genera-> <SqlMapGenerator targetPackage="com.jalja.springmvc_mybatis.mapper" targetProject="./src"><!-- enableSubPackages: Whether to let schema be the suffix of the package --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- enableSubPackages: Whether to let schema be the suffix of the Paquete-> <Property Name = "enableSubpackages" value = "false"/> </sqlmapGenerator> <!-TargetPackage: Ubicación de la generación de interfaz mapper-> <javaclientGenerator type = "xmlmapper" targetPackage = "com.jalja.springmvc_mybatis.mapper" objetivo " habilsubAckages: si debe dejar que el esquema sea el sufijo del paquete-> <propiedad name = "habilsubpackages" valor = "falso"/> </javaclientGenerator> <!-Especifique las tablas de la base de datos-> <table tableName = "items"> </table> <table tableName = "Orders"> </Able> <Arce TableName = "OrderDetail" </Tableil "</table> <Tabla Tabla Tablename =" Orders "> </Ablable> <Tabla Tablename =" OrdenDetail "</</Table> </table> <Tabla Tablename =" Orders "> </ABLE> <TABLE <TABLET TABLE TableName = "User"> </table> </textis> </GeneratorConfiguration> public static void main (string [] arhs) lanza la excepción {list <string> warnings = new ArrayList <String> (); Boolean Overwrite = True; File ConfigFile = New File ("SRC.Main.resources/Generator.xml"); ConfigurationParser CP = New File ("SRC.Main.resources/Generator.xml"); ConfigurationParser CP = New File ("SRC.Main.resources/generador ConfigurationParser (advertencias); configuración config = cp.parseconfiguration (configfile); flowshellCallback callback = new DefaultshellCallback (Overwrite); myBatisGenerator myBatisGenerator = new myBatisGenerator (config, callback, advertencias); myBatisGenerator.generator (null);};};};};};} 2. SpringMVC y MyBatis integran varios archivos de configuración
1. Estructura del proyecto
2. El código central de cada archivo
a.web.xml
<? xml versión = "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> <Devene-File> Index.jsp </Welcome-file> </leadde-file-list> <context-param> <amamname> contextconfiglocation </amamname> <amam-value> classpath: spring/applicationContext-*. Xml </param-value> </textte-param> <searcher> <Oyerer-class> org.springframework.web.context.contextloaderListener </oyeyer-class> </oyeyer> <text-param> <amamname> log4jconfiglocation </aramname> <amarr-value> classpath: log4j.properties </param-value> </context-param> <amamname> log4jrefreshinterval </param-name> <amam-value> 3000 </amam-value> </context-param> <searcher> <searcher-class> org.springframework.web.util.log4jconfiglistener </yorter-class> </oyear> <!-Post Solicitud Código-> <filter> <filter-name> springEncodingFilter </filter-name> <filter-class> org.springframework.web.filter.characterIncodingFilter </filter-class> <it-param> <amamname> codificación </param-name> <amarr-value> utf-8 </param-value> </init-param> <init-param> <amamname> forceEncoding </param-name> <amam-value> true </param-value> </init-param> </filtre> <filter-mapping> <filter-name> springEncodingFilter </filtre-name> <url-pattern>*. do </url-pattern> </filter-mapping> <!-springmvc controlador- <servlet> <servlet-name> springmvc </servlet-name> <ervlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <itel-param> <!-contextConfigLocation Carga el archivo de configuración de SpringMVC (adaptador de procesadores, mapeador) Si no está configurado, la carga predeterminada es/web-Inf/Servlet/Servlet el archivo de configuración (adaptador de procesadores, mapeador) Si no está configurado, la carga predeterminada es/Web-Inf/Servlet/Servlet. name-servlet.xml (springmvc-servlet.xml)-> <amamname> contextConfigLocation </amamname> <amam-value> classpath: spring/springmvc.xml </param-value> </it-param> <carga-on-startup> 1 </load-on-startup> </servlet> <ervlet-xapping> <rapping> <Servlet-name> springmvc </servlet-name> <!-1, *.do: despachadores servlet anotos todos los accesos que terminan en *.do2. /: DispatcherServlet analiza todas las solicitudes (incluidos los recursos estáticos) Esta configuración puede implementar URL3 de estilo Restful,/*: esta configuración eventualmente se reenviará a una página JSP-> <uRl-Pattern>*. <Servlet-class> org.springframework.web.servlet.dispatcherservlet </servlet-class> <itel-param> <amamname> contextconfiglocation </amamname> <amam-value> classpath: spring/applicationcontext-springmvc.xml </param-value> </init-param> <load-on-startup> </servlet> <ervlet-mapping> <servlet-name> springmvc_rest </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>-> <session-config> <session timeOut> 30 </session timeOut> </session-config> </seb-app>
b. config/mybatis/applicationContext-mybatis.xml
<? xml versión = "1.0" encoding = "utf-8"?> < Los parámetros se pueden ajustar cuando MyBatis se ejecuta, como: Habilitar caché secundario, habilitar Typealiases de carga retrasada (alias de tipo): definir el tipo de parámetro Tipo de parámetro Resulttype en mapper.xml Al devolver un tipo, debe especificar la ruta del tipo y no es conveniente desarrollar. Especificaremos el alias para estos tipos. TypeHandler: en MyBatis, la conversión del tipo JDBC y el tipo Java se completa a través de TypeHandler. El procesador proporcionado por MyBatis puede cumplir con los requisitos de desarrollo ObjectFactory: complementos: entornos (Objeto de atributo de recolección de entornos): entorno (objeto sub-attribido de entorno): transaccionManager (administración de transacciones): dataSource (fuente de datos): Mappers (mapper):-> <!-Management de transacciones y configuración de grupos de conexión-> <!-Carga perezosa-> <settings> <! name="lazyLoadingEnabled" value="true"/><!-- Active loading to passive loading--><setting name="aggressiveLazyLoading" value="false"/><!-- Enable Level 2 cache--><setting name="cacheEnabled" value="true"/></settings><typeAliases><!-- Definition for single alias--><!-- <typeAlias Type = "com.jalja.mybatis.model.user" alias = "user"/>-> <!-Definición de alias por lotes mybatis El nombre de clase en el paquete de escaneo automático es el nombre de clase (ambas letras se pueden usar para el caso superior e inferior)-> <paquete = "com.jalja.springmvc_mybatis.model.po name = "com.jalja.springmvc_mybatis.model.custom"/> <paquete name = "com.jalja.springmvc_mybatis.model.vo"/> </typealiases> <!-Cargue el archivo de mapeo-> <!-<Mapeper Resource = "com/jalja/spring_mybatis/mapper/usermapper.xml"/>-> <!-Después de integrarse con Spring, puede eliminar <paquete name = "com.jalja.spring_mybatis.mapper"/> </mappers>-> </figuration>
do. config/spring/applicationContext-dao.xml
<? xml versión = "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://wwww.springframe xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springfrframework http://www.springframework.org/schema/Contextex http://www.springframework.org/schema/contexte/Spring-Contexte-3.2.2.xsd http://wwww.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.orgs/cache/ http://www.springframework.org/schema/cache/spring-cache-3.2.xsd"><!-- Introducción del archivo de configuración de JDBC-> <context: Property-PlaceHolder Ubicación = "classpath: jdbc.Properties"/> <!-Decrypting JDBC Configuración <Bean Id = " name = "ubicaciones"> <list> <valor> classpath: recursos/config/jdbc.properties </value> </list> </propiety> </bean>-> <bean id = "dataSource" destruye-metod = "cerrar"> <name de propiedad = "controlador de controlador"> <valor> $ {jdbc_driverClassName} </valon> </sperty> <property <propiedad> <propiedad </"Property" " nombre = "Url"> <valor> $ {jdbc_Url} </value> </propiety> <Property Name = "UserName"> <Sover> $ {JDBC_USERNAME name = "Maxactive"> <value> 20 </value> </property> <!-Inicializar el tamaño de conexión-> <Property Name = "InitialSize"> <value> 1 </value> </Property> <!-Obtenga el tiempo de espera máximo de espera para la conexión-> <propiedad de propiedad = "MaxWait"> <valor> 60000 </value> </propiétam. name = "maxidle"> <value> 20 </value> </property> <!-Minimum Idleged Connection Pool-> <Property Name = "Minidle"> <value> 3 </value> </Property> <!-Borrar automáticamente la conexión inútil-> <Property Name = "RemoVeABaBaBaBaBaLEd"> <Valor> true </value> </sperte> <!-Clear Waiting Connection para inútiles-> <Property "RemoVeABaBaBaBaBaBaBaBla name = "removeAbaBaBaLedTimeOut"> <value> 180 </value> </property> <!-Propiedades de conexión-> <Property name = "ConnectionProperties"> <alon valor> ClientEncoding = UTF-8 </value> </Property> </bean> <!-Integración perfecta de Spring y MyBatis-> <Bean Id = "Sqlsession Factory"> <Nombre de propiedad = "Datasource" datasource "datasource" datasource "datasource". ref = "DataSource"/> <Property name = "configLocation" value = "classpath: mybatis/applicationContext-mybatis.xml"/> </ bean> <!-Mapper Scanner-> <Bean> <!-Escanee la ruta del paquete si necesita escanear múltiples paquetes, usar una comisión de medio verisas para separarlos-> <nombre de propiedad = "Basepackage" "" Basepackage "" value = "com.jalja.springmvc_mybatis.mapper"/> <propiedad name = "sqlsessionFactoryBeanName" value = "sqlsessionfactory"/> </bean> <!-Gestión de transacciones de transacciones declarativas Gestión de transacciones usando JDBC-> <Bean Id = "TransActionManager"> <Nombre de propiedad = "DataSource" "" DataSource "" ref = "DataSource"> </property> </Bean> <!-Configuración de la notificación de transacciones-> <tx: consejo id = "txadvice" transaccion-ganager = "transaccionManager"> <tx: atributes> <tx: método name = "update*" propagation = "requerido"/> <tx: name de método = "save*" propagation = "requerido"/> <tx n. propagation = "requerido"/> <tx: método name = "get*" propagation = "admite" read-only = "true"/> <tx: método name = "find*" propagation = "admite" reading-only = "true"/> <tx: atributos> </tx: consejo> <!-Configurar el punto de transacción de la transacción y no asociar el punto de la transacción con la transacción con la transacción atribuye con la transacción atribuye -> <aop: config> <aop: asesor consejo-ref = "txadvice" punto = "ejecutivo (*com.jalja.springmvc_mybatis.service.impl.*.*(..))"/> </aop: config> </beachs> D.Config/Spring/ApplicationContext-Service.xml
<? xml versión = "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://wwww.springframe xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/beans http://www.springfrframework http://www.springframework.org/schema/Contextex http://www.springframework.org/schema/contexte/Spring-Contexte-3.2.2.xsd http://wwww.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.springfframework.org/schema/cache/spring-cache-3.2.xsd"> estadounidense id = "itemsService"> </rano> </beans>
E, config/spring/springmvc.xml
<? xml versión = "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://wwww.springframe xmlns: tx = "http://www.springframework.org/schema/tx" xmlns: xsi = "http://www.w3.org/2001/xmlschema-instance http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/Beans http://www.springframework.org/schema/Spring-Beans-3.0.0.xsd 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-cache-3.2.xsd"> ostel Mapper-> <!-mapper org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping springmvc3.1-> <!-mapper org.springframework.web.servlet.mvc.annotation.defaultanTationHandlermapping springmvc3.1-> <!-mApperpepper org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlermapping springmvc3.1 After-> <!-adapter org.springframework.web.servlet.mvc.annotation.annotationmethodleradapter antes de springmvc3.1-> <!-adapter org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter después de SpringMVC3.1-> <!-Configure el mapeador y el adaptador <bean/> <bean/>-> <!-Encienda el mapeador de anotación y el adaptador. Este método carga muchos métodos de enlace de parámetros de forma predeterminada, como el analizador de conversión JSON-> <mvc: annotation-driven/> <!-Configurar el manejador <bean/>-> <!-La configuración de anotación se basa en el método de creación de escaneo-> <context: component-scan base-package = "com.jalja.springmvc_mybatis.controller" parser--><mvc:annotation-driven conversion-service="conversionService"/><bean id="conversionService"><property name="converters"><list><!-- Date type conversion --><bean></bean></list></property></bean><!-- Global exception handler --><bean/><!-- File upload --><!-- Support for uploading files --> <bean id = "MultipResolver"> <!-Size de archivo 5M-> <Property name = "maxUploadSize" value = "5242880"/> </bean> <!-Problema de acceso de recursos estáticos causados por la programación usando estilo restante-> <!-<mvc: mapeo de recursos = "/js/**" ubicación = "/recursos/js/"/"/"/"<!-Spring Intercept a intermed -> <mvc: interceptores> <mvc: interceptor> <mvc: mapping path = "/**"/> <bean/> </mvc: interceptor> </mvc: interceptores> <!-Ver mapa JSP El análisis usa JSTL-> <Bean> <!-Usos predeterminados-> <Nombre de la propiedad = "Viewclass" value = "org.springframework.web.servlet.view.jstlview"/> <propiedad name = "prefix" value = "/web-inf/jsp/"/> <propiedad name = "suffix" value = ". jsp"/> </beans> </beans>
F, config/jdbc.properties
jdbc_driverClassName = com.mysql.jdbc.driverjdbc_url = jdbc: mysql: // localhost: 3306/mybatis? useUnicode = true & caracteresCoding = utf-8JDBC_USElaame = rootjdbc_password = 11111111111111111111111111111111111111111111111111111111111111111111111111111111111111
g, config/log4j.properties
#En el entorno de desarrollo, el nivel de registro debe establecerse para depurar, el entorno de generación debe establecerse en Info o ErrorLog4j.rootlogger = Debug, stdoutlog4j.logger.org.apache.ibatis = debuglog4j.appender.stdout = org.apache.log4j.consoleppenderlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionpattern =%
H, com/jalja/springmvc_mybatis/controler/itemscontroller.java
paquete com.jalja.springmvc_mybatis.controller; import java.io.file; import java.util.list; import java.util.uuid; import org.springframework.beanss.factory.annotation.aUtowired; import org.springframework.stereotype. org. org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.requestparam; import org.springframework.web.bind.annotation.reSponseBody; import og.springframework.web.multultipart; com.jalja.springmvc_mybatis.Exception.CustOmEcception SpringMVC proporciona muchos convertidores de parámetros*/@controlador@requestmapping ("/elementos") // mapeo de solicitudes estrechas de clase pública itemScontroller {@aUtowired itemsService itemsService; @RequestMapping (valor = "/findemslist") Cadena pública FindImslist (modelo Modelo) arroja excepción {Listscustom> itemsList=itemsService.findItemsList(null);System.out.println(itemsList);model.addAttribute("itemsList", itemsList);return "itemsList";}@RequestMapping(value="/editItems", method={RequestMethod.POST,RequestMethod.GET}) //Limit the Http request method//@RequestParam Bind the request Parámetros con los parámetros formales requeridos: especifique que el valor del atributo debe aprobarse en defaultValue: Establecer el valor predeterminado public String editEtems (modelo modelo, @requestparam (valor = "id", requerido = true, defaultValue = "0") Integer ElementsId) Exception {itemScustom itemsCustom = itemservice.FindInsByid (itemsitsid); if (if (if (if (if (itemScustom). nueva customexception ("el producto no existe");} model.addattribute ("itemScustom", itemScustom); return "editItems";}@requestmapping (value = "/updateItems") public String editEtemsSubMit (ID de Integer, itemScustom itemScustom, multipartfile elementos) lanza la excepción {String {String {String {String {String {String {String {String {String {String {String {String {String {String {String {String {Striz uploadFileName = itemspic.getoriginalFileName (); // Obtenga el nombre de archivo cargado if (itemsPic! = null && uploadFileName! = null &&! uploadFileName.equals ("")) {String IGRACET = "e: // Desarrollar // upload // images //; string newFileName = uuid.randomuuid ()+uploadFileName.substring (uploadFileName.lastIndexof ("."), uploadFileName.length ()); archivo newfile = nuevo archivo (ImagePath+newFileName); ElememSpic.transferto (newfile); // Datos de escritura en la memoria a la memoria de Disk a Disk. itemScustom.setPic (newFileName);} itemsService.UpdateItemSById (id, itemScustom); return "redirect: findItemSlist.do"; // Redirect} // Uso de JSON @ResponseBody: para objetar la salida de JSON @RequestBody: para solicitar parámetros a Java Object @RequestMapping (valor = "/JSONREQUEST") public @ResponseBody itemscustom jSonRequest (@RequestBody Elemscustom itemscustom) lanza la excepción {return itemScustom;} /////////estilo restaurante Programming/RestfulRequest/{id}: significa pasar el parámetro en esta posición al nombre especificado por @PathVariable @RequestMapping (valor = "/RestfulRequest/{id}") public @ResponseBody itemScustom RestfulRequest (@PathVariable ("ID") ID de intento) Excepción {itemScustomScustomScustom itemScustom = itemsService.FindItemSById (id); return itemScustom;}}Lo anterior es el código de ejemplo de mybatis integrado de SpringMVC introducido por el editor. Espero que te sea útil. Si desea saber más información, ¡preste atención al sitio web de Wulin.com!