MyBatis is an open source project of apache. In 2010, this project was moved from apache software foundation to Google code and was renamed MyBatis.
1. Reverse engineering generates basic information
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"><generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><commentGenerator><!-- Whether to remove the auto-generated comments true: Yes: false: No--><property name="suppressAllComments" value="true" /></commentGenerator><!--Database connection information: driver class, connection address, username, password--><jdbcConnection driverClass="com.mysql.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3307/mybatis" userId="root"password="jalja"></jdbcConnection><!-- Default false, parse the JDBC DECIMAL and NUMERIC types into Integer, and when true, JDBC DECIMAL and NUMERIC Type resolves to java.math.BigDecimal --><javaTypeResolver><property name="forceBigDecimals" value="false" /></javaTypeResolver><!-- targetProject: Location of the PO class generated --><javaModelGenerator targetPackage="com.jalja.springmvc_mybatis.model.pojo"targetProject="./src"><!-- enableSubPackages: Whether to let schema be the suffix of the package --><property name="enableSubPackages" value="false" /><!-- The spaces before and after the value returned from the database are cleaned --><property name="trimStrings" value="true" /></javaModelGenerator><!-- targetProject: Where the mapper map file is generated --><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 package --><property name="enableSubPackages" value="false" /></sqlMapGenerator><!-- targetPackage: Location of mapper interface generation --><javaClientGenerator type="XMLMAPPER"targetPackage="com.jalja.springmvc_mybatis.mapper" targetProject="./src"><!-- 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) throws Exception{List<String> warnings = new ArrayList<String>();boolean overwrite = true;File configFile = new File("src.main.resources/generator.xml");ConfigurationParser cp = new ConfigurationParser(warnings);Configuration config = cp.parseConfiguration(configFile);DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);myBatisGenerator.generate(null);} 2. SpringMVC and Mybatis integrate various configuration files
1. Project structure
2. The core code of each file
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> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param><param-name>contextConfigLocation</param-name><param-value> classpath:spring/applicationContext-*.xml </param-value></context-param><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>classpath:log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>3000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <!-- Post request garbled code--><filter><filter-name>SpringEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value> </init-param><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>SpringEncodingFilter</filter-name><url-pattern>*.do</url-pattern></filter-mapping> <!-- springMvc front-end controller--> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- contextConfigLocation loads springMvc's configuration file (processor adapter, mapper) If not configured, the default loading is /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 :DispatcherServlet parses all accesses ending in *.do2. / :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> --><session-config><session-timeout>30</session-timeout></session-config></web-app>
b. 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> <!-- Each property properties: setting (global configuration parameter configuration): some running parameters can be adjusted when mybatis run, such as: enable secondary cache, enable delayed loading typeAliases (type alias): define parameterType parameter type resultType in mapper.xml When returning a type, you need to specify the path of the type and it is not convenient to develop. We will specify the alias for these types. TypeHandler: In mybatis, the conversion of jdbc type and java type is completed through typeHandler. The processor provided by mybatis can meet the development requirements objectFactory: plugins: environments (environments collection attribute object): environment (environment sub-attribute object): transactionManager (transaction management): dataSource (data source): mappers (mapper): --><!-- Management of transactions and configuration of connection pools--> <!-- Lazy Loading--><settings><!-- Open lazy loading--><setting 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"/> --><!-- Definition of batch alias mybatis The class name in the automatic scanning package is the class name (both first letters can be used for upper and lower case) --><package name="com.jalja.springmvc_mybatis.model.pojo"/><package name="com.jalja.springmvc_mybatis.model.custom"/><package name="com.jalja.springmvc_mybatis.model.vo"/></typeAliases><!--Load the mapping file--><!-- <mappers> <mapper resource="com/jalja/spring_mybatis/mapper/UserMapper.xml"/> --><!-- After integrating with spring, you can remove <package name="com.jalja.spring_mybatis.mapper"/> </mappers>--></configuration>
c. config/spring/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.springframework.org/schema/mvc" 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 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-3.2.xsd 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"><!-- Introducing jdbc configuration file--><context:property-placeholder location="classpath:jdbc.properties"/> <!-- Decrypting JDBC configuration<bean id="propertyConfigurer"> <property name="locations"><list><value>classpath:resources/config/jdbc.properties</value></list></property></bean> --><bean id="dataSource" destroy-method="close"><property name="driverClassName"><value>${jdbc_driverClassName}</value></property><property name="url"><value>${jdbc_url}</value></property><property name="username"><value>${jdbc_username}</value></property><property name="password"><value>${jdbc_password}</value></property><!-- Maximum number of connections used in connection pool--><property name="maxActive"><value>20</value></property><!-- Initialize the connection size--><property name="initialSize"><value>1</value></property><!-- Get the maximum waiting time for connection--><property name="maxWait"><value>60000</value></property><!-- Maximum idle connection pool--><property name="maxIdle"><value>20</value></property><!-- Minimum idle connection pool--><property name="minIdle"><value>3</value></property><!-- Automatically clear useless connection--><property name="removeAbandoned"><value>true</value></property><!-- Clear waiting time for useless connection--><property name="removeAbandonedTimeout"><value>180</value></property><!-- Connection properties--><property name="connectionProperties"><value>clientEncoding=UTF-8</value></property></bean><!-- Perfect integration of spring and MyBatis--> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatis/applicationContext-mybatis.xml"/></bean> <!-- Mapper scanner--><bean> <!-- Scan the package path If you need to scan multiple packages, use a half-width comma to separate them--><property name="basePackage" value="com.jalja.springmvc_mybatis.mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- Declarative Transaction Management Transaction Management Using jdbc--><bean id="transactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- Configuring Transaction Notification--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="update*" propagation="REQUIRED"/><tx:method name="save*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="get*" propagation="SUPPORTS" read-only="true"/><tx:method name="find*" propagation="SUPPORTS" read-only="true"/><tx:attributes></tx:advice><!-- Configure transaction point-insert and do not associate transaction point-insert with transaction attributes AOP --><aop:config><aop:advisor advice-ref="txAdvice" pointcut="execution(* com.jalja.springmvc_mybatis.service.impl.*.*(..))"/></aop:config></beans> d.config/spring/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.springframework.org/schema/mvc" 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 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-3.2.xsd 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"><bean id="itemsService"></bean></beans>
e, config/spring/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.springframework.org/schema/mvc" 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 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.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/spring-cache-3.2.xsd"><!--Annotation Processor Mapper--><!-- Mapper org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping springmvc3.1--> <!-- Mapper org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping springmvc3.1--> <!-- Mapper org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping springmvc3.1 after --><!-- Adapter org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter before springmvc3.1--> <!-- Adapter org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter after springmvc3.1--><!-- Configure mapper and adapter<bean/><bean/> --><!-- Turn on the annotation mapper and adapter. This method loads many parameter binding methods by default, such as json conversion parser--><mvc:annotation-driven/><!-- Configure Handler<bean/>--><!-- Annotation configuration is based on the method of building scanning--><context:component-scan base-package="com.jalja.springmvc_mybatis.controller" /><!-- Configure custom parameter 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="multipartResolver"><!-- File size 5M --><property name="maxUploadSize" value="5242880"/></bean> <!-- Static resource access problem caused by programming using restFul style--><!-- <mvc:resources mapping="/js/**" location="/resources/js/"/> --><!-- springMVC interceptor configuration --><mvc:interceptors><mvc:interceptor><mvc:mapping path="/**" /><bean /></mvc:interceptor></mvc:interceptors><!-- View map jsp parsing uses jstl--><bean><!-- Default uses --><property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /><property name="prefix" value="/WEB-INF/jsp/" /><property name="suffix" value=".jsp" /></bean> </beans>
f, config/jdbc.properties
jdbc_driverClassName=com.mysql.jdbc.Driverjdbc_url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8jdbc_username=rootjdbc_password=111111
g, config/log4j.properties
#In the development environment, the log level should be set to debug, the generation environment should be set to info or errorlog4j.rootLogger=debug, 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
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.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import com.jalja.springmvc_mybatis.exception.CustomException;import com.jalja.springmvc_mybatis.model.custom.ItemsCustom;import com.jalja.springmvc_mybatis.service.ItemsService;/*** Product* @author PC003*conterver Parameter Converter springMvc provides many parameter converters*/@Controller@RequestMapping("/items") //Narrow request mapping public class ItemsController {@Autowired ItemsService itemsService;@RequestMapping(value="/findItemsList")public String findItemsList(Model model) throws Exception{List<ItemsCustom> 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 parameters with formal parameters required: specify that the value of the attribute must be passed in defaultValue: Set the default value public String editItems(Model model, @RequestParam(value="id", required=true,defaultValue="0") Integer itemsId) throws Exception{ItemsCustom itemsCustom=itemsService.findItemsById(itemsId);if(itemsCustom=null){throw new CustomException("Product does not exist");}model.addAttribute("itemsCustom", itemsCustom);return "editItems";}@RequestMapping(value="/updateItems")public String editItemsSubmit(Integer id,ItemsCustom itemsCustom,MultipartFile itemsPic) throws Exception{String uploadFileName=itemsPic.getOriginalFilename();//Get the uploaded file name if(itemsPic!=null && uploadFileName!=null && !uploadFileName.equals("")){String imagesPath="E://develop//upload//images//";String 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.updateItemsById(id, itemsCustom);return "redirect:findItemsList.do"; //Redirect}//Use of JSON @ResponseBody: To object to json output @RequestBody: To request parameters to java object @RequestMapping(value="/jsonRequest")public @ResponseBody ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) throws Exception{return itemsCustom;}//RestFul Style Programming/restFulRequest/{id}: It means to pass the parameter at this position to the name specified by @PathVariable @RequestMapping(value="/restFulRequest/{id}")public @ResponseBody ItemsCustom restFulRequest(@PathVariable("id") Integer id) throws Exception{ItemsCustom itemsCustom=itemsService.findItemsById(id);return itemsCustom;}}The above is the SpringMVC integrated mybatis example code introduced to you by the editor. I hope it will be helpful to you. If you want to know more information, please pay attention to the Wulin.com website!