SpringMVC mybatis integration example code detail
- 2020-07-21 07:36:14
- OfStack
MyBatis was originally an open source project of apache. In 2010, the project was transferred from apache software foundation to google code and renamed MyBatis.
1. Reverse engineering to generate basic information
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//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 auto-generated comments true Is: : 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"
passaspku.com/pc/softtech/office/word/" target="_blank"><u>word</u>="jalja">
</jdbcConnection>
<!-- The default false , JDBC DECIMAL and NUMERIC Type resolution is Integer for true When the JDBC DECIMAL and
NUMERIC Type resolution is java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject: generate PO The location of the class -->
<javaModelGenerator targetPackage="com.jalja.springmvc_mybatis.model.pojo"
targetProject=".\src">
<!-- enableSubPackages: Whether to let schema As a suffix for packages -->
<property name="enableSubPackages" value="false" />
<!-- The values returned from the database are cleaned up with and without Spaces -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper The location where the mapping file is generated -->
<sqlMapGenerator targetPackage="com.jalja.springmvc_mybatis.mapper"
targetProject=".\src">
<!-- enableSubPackages: Whether to let schema As a suffix for packages -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage : mapper The location where the interface is generated -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.jalja.springmvc_mybatis.mapper"
targetProject=".\src">
<!-- enableSubPackages: Whether to let schema As a suffix for packages -->
<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 each configuration file
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/javaee
http://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 the 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 controller -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!--
contextConfigLocation loading springMvc Configuration file of ( Processor adapter The mapper )
If not configured to load by default is /WEB-INF/servlet The name of the -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-name>springMvc</servlet-name>
<!--
1 , *.do :DispatcherServlet Parse all *.do Closing visit
2 , / :DispatcherServlet Resolve all requests (including static resources) This configuration can be implemented restful In the style of url
3 , /*: This configuration will eventually be forwarded to 1 a jsp page
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- springMvc Front 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 attribute
properties :
setting (Global configuration parameter configuration) : mybatis You can adjust it at runtime 1 Some running parameters For example: turn on 2 Level I cache and enable lazy loading
typeAliases( Type the alias ): in mapper.xml Defined in the parameterType The parameter types resultType Return type
You need to specify a path of type Not convenient to develop, we open 1 for These types give them aliases
typeHandler( Type processor ): in mybatis Is through typeHandler complete jdbc The type and java Conversion of types . mybatis The supplied processor is available Development needs
objectFactory( Object factory ) :
plugins( The plug-in ):
environments( Environment collection property object ):
environment (Environment subproperty object) :
transactionManager( Transaction management ):
dataSource( The data source ):
mappers( mapper ):
-->
<!-- Transaction management and connection pool configuration -->
<!-- Lazy loading -->
<settings>
<!-- Open lazy loading -->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- Positive load changed to negative load -->
<setting name="aggressiveLazyLoading" value="false"/>
<!-- open 2 Level cache -->
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<!-- Definition for a single alias -->
<!-- <typeAlias type="com.jalja.myBatis.model.User" alias="user"/> -->
<!-- Definition of batch alias mybatis Automatically scans classes in packages An alias is the name of the class (either upper or 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 mapping file -->
<!-- <mappers> <mapper resource="com/jalja/spring_mybatis/mapper/UserMapper.xml"/> -->
<!-- and spring After the integration Can be removed
<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.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<!-- The introduction of jdbc The configuration file -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- right JDBC Configure decryption
<bean id="propertyConfigurer" class="cn.com.sinobpo.project.wfjb.utils.EncryptablePropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:resources/config/jdbc.properties</value>
</list>
</property>
</bean> -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 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>
<!-- The maximum number of connections used in the connection pool -->
<property name="maxActive">
<value>20</value>
</property>
<!-- Initializes the connection size -->
<property name="initialSize">
<value>1</value>
</property>
<!-- Gets the maximum wait time for a connection -->
<property name="maxWait">
<value>60000</value>
</property>
<!-- Maximum free connection pool -->
<property name="maxIdle">
<value>20</value>
</property>
<!-- Minimum idle connection pool -->
<property name="minIdle">
<value>3</value>
</property>
<!-- Automatically clears unwanted connections -->
<property name="removeAbandoned">
<value>true</value>
</property>
<!-- Clear the wait time for unwanted connections -->
<property name="removeAbandonedTimeout">
<value>180</value>
</property>
<!-- Connection properties -->
<property name="connectionProperties">
<value>clientEncoding=UTF-8</value>
</property>
</bean>
<!-- spring and MyBatis Perfect integration -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis/applicationContext-mybatis.xml"/>
</bean>
<!-- use mapper The agent The way of mapper The scanner -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- Scan packet path If multiple packages need to be scanned , separated by a half-corner comma -->
<property name="basePackage" value="com.jalja.springmvc_mybatis.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- declarative Transaction management use jdbc Transaction management of -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- Configure transaction notifications -->
<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 pointcuts for transactions , The transaction pointcut is not associated with the transaction property 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.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<bean id="itemsService" class="com.jalja.springmvc_mybatis.service.impl.ItemsServiceImpl"></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.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
<!-- annotations The processor mapper -->
<!-- mapper org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping springmvc3.1 before -->
<!-- mapper org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping springmvc3.1 after -->
<!-- The adapter org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter springmvc3.1 before -->
<!-- The adapter org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter springmvc3.1 after -->
<!-- Configure the mapper and The adapter
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
<!-- Open the annotation The mapping and The adapter This method loads many parameter binding methods by default For example, json Conversion parser -->
<mvc:annotation-driven/>
<!-- configuration Handler
<bean class="com.jalja.springmvc_mybatis.controller.UserController"/>-->
<!-- annotations configuration Based on how the build scan works -->
<context:component-scan base-package="com.jalja.springmvc_mybatis.controller" />
<!-- Configure the custom parameter parser -->
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- Date type conversion -->
<bean class="com.jalja.springmvc_mybatis.converter.CustomDateConverter"></bean>
</list>
</property>
</bean>
<!-- Global exception handler -->
<bean class="com.jalja.springmvc_mybatis.exception.CustomExceptionResolver"/>
<!-- File upload -->
<!-- Support for uploading files -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- The file size 5M -->
<property name="maxUploadSize" value="5242880"/>
</bean>
<!-- use restFul style programming According to the Static resource access The problem -->
<!-- <mvc:resources mapping="/js/**" location="/resources/js/"/> -->
<!-- springMVC Configuration of interceptors -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.jalja.springmvc_mybatis.interceptor.LoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- View map jsp parsing Use the default jstl-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Use the default -->
<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.Driver
jdbc_url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
jdbc_username=root
jdbc_password=111111
g, config/log4j properties
# The level of logging in the development environment To set up debug , the generation environment is set to info or error
log4j.rootLogger=debug, stdout
log4j.logger.org.apache.ibatis=debug
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.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;
/**
* goods
* @author PC003
*conterver Parameter converter springMvc A number of parameter converters are provided
*/
@Controller
@RequestMapping("/items") // Narrow the request map
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 Http Request way
//@RequestParam Request parameters with Formal parameters are bound required: Specifies that the property must pass in a value defaultValue: Set default values
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(" Goods don't 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();// Gets the file name of the upload
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);// Writes data from memory to disk
itemsCustom.setPic(newFileName);
}
itemsService.updateItemsById(id, itemsCustom);
return "redirect:findItemsList.do"; // redirect
}
//JSON The use of @ResponseBody : Will rotate the image json The output @RequestBody: Turn the request parameter java object
@RequestMapping(value="/jsonRequest")
public @ResponseBody ItemsCustom jsonRequest(@RequestBody ItemsCustom itemsCustom) throws Exception{
return itemsCustom;
}
//RestFul style programming /restFulRequest/{id} : means to pass the parameter to this position @PathVariable In the specified name
@RequestMapping(value="/restFulRequest/{id}")
public @ResponseBody ItemsCustom restFulRequest(@PathVariable("id") Integer id) throws Exception{
ItemsCustom itemsCustom=itemsService.findItemsById(id);
return itemsCustom;
}
}
I hope you found this example helpful