由于spring4+支持泛型,这个特性对通用Mapper来说,非常的有用,可以说有了这个特性我们就可以继承通用的Mapper<T>实现crud的操作,节省了我们开发的时间。
以往我们使用mapper文件都是自己写sql语句,针对的是单个实体,也就是每个实体都有其对应的mapper文件。使用通用mapper给我们带来了极大的方便,通用mapper里面有许多我们常用的接口,平时开发90%的crud操作都在里面,只需我们调用相应的接口,引入jar包再进行简单的配置就好了。
这是一位大佬的开源项目,想学习的可以去他的github点击打开链接
这里我整合了一个springmvc的通用mapper例子
首先在pom.xml中添加对通用mapper的支持,其他的和springmvc一致
<!--通用Mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mapper.version}</version> </dependency>
插件配置
<plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>${mapper.version}</version> </dependency> </dependencies> </plugin>
通用 Mapper 支持 MyBatis 3.2.4+,我这里用的mybatis版本是3.4.6,spring的版本是4.1.2,mybatis.spring的版本是1.3.1,mapper的版本是4.0.0
如果版本不匹配的话会出现错误如下
错误org.mybatis.spring.transaction.SpringManagedTransaction.getTimeout()Ljava/lang/Integer;
解决方法:更换Spring_Mybatis整合包版本,具体版本对照如下
MyBatis-Spring | MyBatis | Spring |
1.0.0 and 1.0.1 | 3.0.1 to 3.0.5 | 3.0.0 or higher |
1.0.2 | 3.0.6 | 3.0.0 or higher |
1.1.0 or higher | 3.1.0 or higher | 3.0.0 or higher |
1.3.0 or higher | 3.4.0 or higher | 3.0.0 or higher |
项目结构图
1.web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID1" version="3.0"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mybatis.xml</param-value> </context-param> <filter> <description>字符集过滤器</description> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <description>字符集编码</description> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <description>spring监听器</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class> </listener> <servlet> <description>spring mvc servlet</description> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>spring mvc 配置文件</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.jpg</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.js</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.css</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.png</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.gif</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <session-config> <session-timeout>60</session-timeout> </session-config> </web-app>
2.spring-mybatis.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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd "> <!-- Spring:配置扫描容器,不扫描Controller和ControllerAdvice注解 --> <context:component-scan base-package="com.smxy.lq"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 引入属性文件 --> <context:property-placeholder location="classpath:config.properties" /> <!-- 配置数据源 --> <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 初始化连接大小 --> <property name="initialSize" value="0" /> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="20" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="20" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="60000" /> <property name="validationQuery" value="${validationQuery}" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="testWhileIdle" value="true" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> <!-- 打开removeAbandoned功能 --> <property name="removeAbandoned" value="true" /> <!-- 1800秒,也就是30分钟 --> <property name="removeAbandonedTimeout" value="1800" /> <!-- 关闭abanded连接时输出错误日志 --> <property name="logAbandoned" value="true" /> <!-- 监控数据库 --> <!-- <property name="filters" value="stat" /> --> <property name="filters" value="mergeStat" /> </bean> <!-- MyBatis配置 这个就是spring和mybatis的整合 也就是spring-mybatis jar --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--数据库的数据源配置 --> <property name="dataSource" ref="dataSource" /> <!-- mysqlSqlSessionFactory会自动扫描该路径下的所有文件并解析。 --> <property name="mapperLocations" value="classpath:mapper/*.xml" /> <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 ,该属性可以给包中的类注册别名,注册后可以直接使用类名,而不用使用全限定的类名 --> <property name="typeAliasesPackage" value="com.smxy.lq.pojo" /> </bean> <!--在Spring中配置Mapper接口 --> <bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 为映射器接口文件设置基本的包路径 --> <property name="basePackage" value="com.smxy.lq.mapper" /> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate" scope="prototype"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 注解方式配置事物 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 拦截器方式配置事物 --> <tx:advice id="transactionAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="append*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="modify*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="repair" propagation="REQUIRED" /> <tx:method name="delAndRepair" propagation="REQUIRED" /> <tx:method name="get*" propagation="SUPPORTS" /> <tx:method name="find*" propagation="SUPPORTS" /> <tx:method name="load*" propagation="SUPPORTS" /> <tx:method name="search*" propagation="SUPPORTS" /> <tx:method name="datagrid*" propagation="SUPPORTS" /> <tx:method name="*" propagation="SUPPORTS" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.smxy.lq.service..*Impl.*(..))" /> <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" /> </aop:config> <!-- 配置druid监控spring jdbc --> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> </bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>com.smxy.lq.service.*</value> <value>com.smxy.lq.serviceimpl.*</value> </list> </property> </bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> </aop:config> </beans>
3.spring-mvc配置
<?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"> <!-- 1.SpringMvc:配置容器扫描只扫描Controller注解和ControllerAdvice注解 --> <context:component-scan base-package="com.smxy.lq" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 2.配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 3.处理静态资源 --> <mvc:default-servlet-handler /> <mvc:annotation-driven></mvc:annotation-driven> <!-- 4.文件上传,配置MultipartResolver 使用spring的CommosMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的最大尺寸为5MB --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean> <!-- 5.全局异常处理器 只要实现HandlerExceptionResolver接口就是全局异常处理器 --> <!-- <bean class="com.smxy.study.exception.ErrorExceptionResolver"></bean> --> </beans>
4.generatorConfig.xml配置,可以产生代码的工具,之前有一篇博客上介绍如何使用 地址:点击打开链接
<?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> <properties resource="config.properties"/> <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/> <property name="caseSensitive" value="true"/> </plugin> <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.url}" userId="${jdbc.user}" password="${jdbc.password}"> </jdbcConnection> <javaModelGenerator targetPackage="com.smxy.lq.pojo" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <javaClientGenerator targetPackage="com.smxy.lq.mapper" targetProject="src/main/java" type="XMLMAPPER"/> <table tableName="country"> <generatedKey column="id" sqlStatement="JDBC"/> </table> </context> </generatorConfiguration>
产生完的mapper都会继承Mapper这个接口,这个Mapper接口里面有需要我们常用的crud方法,这里面可以什么都不要写,只要在Service里面写上方法就行了。
5.Service里面写上自定义方法
package com.smxy.lq.service; import com.smxy.lq.pojo.Country; public interface CountryService { // 查找 public Country findCountryById(Integer id) throws Exception; // 删除 public void delectCountryById(Integer id) throws Exception; // 插入 public void insertCountry(Country country) throws Exception; // 修改 public void updateCountry(Country country) throws Exception; }
6.实现类重写该方法,并注入mapper,使用通用mapper方法实现crud操作,通用方法有很多,可自行尝试,我这里只有简单的增删改查四个
7.在controller层使用
package com.smxy.lq.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.smxy.lq.pojo.Country; import com.smxy.lq.service.CountryService; @Controller public class CountryController { @Autowired CountryService countryService; @RequestMapping("/findcountry") public @ResponseBody Country findcountry() throws Exception{ return countryService.findCountryById(1); } @RequestMapping("/delectCountryById") public void delectCountryById() throws Exception{ countryService.delectCountryById(1); } @RequestMapping("/insertCountry") public void insertCountry() throws Exception{ Country country=new Country(); country.setCountryname("asdfasdf"); country.setCountrycode("asdfasdf"); countryService.insertCountry(country); } @RequestMapping("/updateCountry") public void updateCountry() throws Exception{ Country country=new Country(); country.setId(3); country.setCountryname("asdfasdf"); country.setCountrycode("asdfasdf"); countryService.updateCountry(country); } }