I haven't written a few articles since I opened the garden for so many years. Now I think it's not good to just read other people's articles. I'll write it myself. Just write about the problems I met when I was doing the integration of spring mvc and mybatis on this day.
1 spring and mybatis integration
I believe everyone has done it, but I still want to talk about it. First of all, we have to put up the general shelf of the project. I use IDEA, not much nonsense to say the above picture.
This is the structure of my spring and mybatis projects, which I believe everyone can see, and I don't need to say much. In fact, the most important thing is the application Context. XML file.
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/aop 8 http://www.springframework.org/schema/aop/spring-aop.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx.xsd"> 13 14 15 16 <context:component-scan base-package="com.kevin.learn.testspringmybatis.service.*" /> 17 18 <bean id="propertyConfigurer" 19 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 20 <property name="location" value="classpath:jdbc.properties" /> 21 </bean> 22 23 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" 24 init-method="init" destroy-method="close"> 25 <property name="driverClassName" value="${driver}" /> 26 <!-- Basic attributes url,user,password --> 27 <property name="url" value="${url}" /> 28 <property name="username" value="${user}" /> 29 <property name="password" value="${pwd}" /> 30 31 <!-- Configuration initialization size, minimum, maximum --> 32 <property name="initialSize" value="1" /> 33 <property name="minIdle" value="1" /> 34 <property name="maxActive" value="20" /> 35 36 <!-- Configuration to get the connection waiting timeout time --> 37 <property name="maxWait" value="60000" /> 38 39 <!-- How often is the configuration interval detected to detect idle connections that need to be closed in milliseconds? --> 40 <property name="timeBetweenEvictionRunsMillis" value="60000" /> 41 42 <!-- Configure the minimum lifetime of a connection in the pool in milliseconds --> 43 <property name="minEvictableIdleTimeMillis" value="300000" /> 44 </bean> 45 46 <!--spring and mybatis Combined bean--> 47 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 48 <property name="dataSource" ref="dataSource" /> 49 <property name="mapperLocations" value="classpath:com/kevin/learn/testspringmybatis/sqlmapper/*.xml"/> 50 </bean> 51 <!--Automatic Scanning dao Interface and mapper File binding--> 52 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 53 <property name="basePackage" value="com.kevin.learn.testspringmybatis.dao" /> 54 <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> 55 </bean> 56 57 <!--Here are the transactions--> 58 <bean id="transactionManage" 59 class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 60 <property name="dataSource" ref="dataSource"></property> 61 </bean> 62 <tx:advice id="transactionAdvice" transaction-manager="transactionManage"> 63 <tx:attributes> 64 <tx:method name="*" propagation="REQUIRED" rollback-for="java.lang.Exception" 65 isolation="DEFAULT" /> 66 <tx:method name="get*" read-only="true" /> 67 </tx:attributes> 68 </tx:advice> 69 <aop:config> 70 <aop:advisor advice-ref="transactionAdvice" 71 pointcut="execution(* com.kevin.springmvc.service.*.*(..))" /> 72 </aop:config> 73 74 </beans>
This configuration is very simple, but it's the combination of spring and mybatis that makes me underestimate the integration of spring mvc and mybatis, and the class libraries where all the code is referenced by pom files in a package are generally not a problem.
2 spring mvc and mybatis
First look at the general framework of the project.
That's a clear point, too.
Let's start with the web project. We use servlet 3.1 here. Many people will make mistakes in this schema, because the web.xml of the web skeleton project that maven defaults to is a bit too personal, and it's too troublesome to move that skeleton file, so I'll post it all.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Spring Mvc Web Application</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring/app*.xml </param-value> </context-param> <!-- Context listener --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring Support --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
In this spring servlet, I don't use the default one under web-info. I'm passing in a specified xml springmvc-servlet.xml to Spring's Dispatcher Servlet under resource.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- Scanning the package automatically SpringMVC Think the package is used.@controller The annotated class is the controller --> <context:component-scan base-package="com.kevin.springmvc.web.controller" /> <mvc:annotation-driven /><!--This must be noted.,tomcat You can run without writing,It's not necessarily on other containers.-->
<!--View Desktop--> <mvc:view-resolvers> <mvc:jsp cache-views="false" prefix="/WEB-INF/jsp/" suffix=".jsp" /> </mvc:view-resolvers> <!--json--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <description>annotation controller Method adapter</description> <property name="messageConverters"> <list><!--JSON Converter --> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes" value="application/json;charset=UTF-8" /> </bean> </list> </property> </bean> </beans>
In this configuration file, I encountered a small problem, that is, the red label in my file. It's okay how to start the operation under tomcat. Before I changed tomcat, I used tomEE to start up, and I always made a mistake. I said what happened, and then I began to check little by little to find that this thing was not added. No, Tomcat after adding
It's okay to try it. Well, I think I'll do it with more rigorous verification for other containers, or with my tomee.
After that, the following is the integration of spring and mybatis. Before, I took the configuration file of spring and mybatis directly above, but the file was too messy, all things in one piece were not conducive to modification. Here I separated them, because I was only a simple integration, I divided them into three files.
app-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Introducing attribute files --> <context:property-placeholder location="classpath:jdbc.properties"/> <context:component-scan base-package="com.kevin.springmvc.service.*"/> </beans>
This simplicity only introduces configuration files and automatic scanning
app-datasource.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${driver}"/> <!-- Basic attributes url,user,password --> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${pwd}"/> <!-- Configuration initialization size, minimum, maximum --> <property name="initialSize" value="1"/> <property name="minIdle" value="1"/> <property name="maxActive" value="20"/> <!-- Configuration to get the connection waiting timeout time --> <property name="maxWait" value="60000"/> <!-- How often is the configuration interval detected to detect idle connections that need to be closed in milliseconds? --> <property name="timeBetweenEvictionRunsMillis" value="60000"/> <!-- Configure the minimum lifetime of a connection in the pool in milliseconds --> <property name="minEvictableIdleTimeMillis" value="300000"/> </bean> </beans>
That's fine. There's a connection pool and nothing else.
app-mybatis.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <description>spring and MyBatis Perfect integration, no need mybatis Configuration mapping file</description> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis/mybatis-config.xml" /> <!-- Automatic Scanning mapping.xml file --> <property name="mapperLocations" value="classpath*:com/kevin/springmvc/dao/sqlmapper/*.xml" /> <property name="typeAliasesPackage" value="com.kevin.springmvc.beans" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <description>DAO The package name of the interface, Spring The following classes are automatically found</description> <property name="basePackage" value="com.kevin.springmvc.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- affair --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> </beans>
There's nothing to say about it. Just split the file and use it.
mybatis-config.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> <settings> <! - Global Mapper Enables Caching - > <setting name="cacheEnabled" value="true" /> <! - Turn off immediate loading of associated objects to improve performance when querying <setting name="lazyLoadingEnabled" value="true" /> <! -- Set the loading form of the association object, where the field is loaded on demand (the loading field is specified by SQL), and all fields of the association table will not be loaded to improve the performance - > <setting name="aggressiveLazyLoading" value="false" /> <! - For unknown SQL queries, different resu lt sets are allowed to be returned to achieve a general effect - > <setting name="multipleResultSetsEnabled" value="true" /> <! - Allow column labels to replace column names - > <setting name="useColumnLabel" value="true" /> <! - Allows the use of custom primary key values (such as UUID 32-bit codes generated by the program as key values), and the PK generation strategy of the data table will be overridden - > <setting name="useGeneratedKeys" value="true" /> <! - Give nested resu lt Map field-attribute mapping support - > 2. <setting name="autoMappingBehavior" value="FULL" /> <! - Caching SQL for batch update operations to improve performance <setting name="defaultExecutorType" value="BATCH" /> <! - If the database has not responded for more than 25,000 seconds, it will be timed out. <setting name="defaultStatementTimeout" value="25000" /> </settings> </configuration>
This is some of the global settings for mybatis
All of these configuration files have been made, and the basic maven references have been finished. It seems that they can run. I'm wrong. That's the beginning of my nightmare. Once they run, they're all wrong.
1 Data Source Error
I was speechless at that time, the database was ready, maven quoted it, so it shouldn't be, and then a good look, first read the error report can't find the database driver, oh oh oh oh, know parent's maven quotation I added, but under the web project I did not add ah, this is not wrong, but the problem came again.
2. The mapper file of mybatis is not bound to the interface file. The statment can not be found in the report.
I'm going to say that my mapper file is not placed in the resource folder of the web, I put it in dao and the data access interface in a module, but Maven will not package the xml file into the jar file when it generates the jar file, which requires us to set up the maven file.
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory> src/main/resources </directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
That's the node of resources, and it's all right with it. Okay, now I can go with everything.
When I do this, I have seen a lot of problems on the internet. In my opinion, most of them are caused by the lack of references to maven files. Let's check the relevant documents carefully, then put them under idea and run them with tomcat. The error of this report is still cleared up and analyzed. Before, I used eclipse and Tomcat to report errors, which is not clear. Chu, some can't be checked.
Well, maybe I don't use eclipse very well. Don't spray me.
Okay, the above two are what I met when I was doing spring mvc. In some cases, I just make a summary.
In a word, we should be careful and careful again.