1.本例环境
1>. spring + mybatis + eclipse Mars + 基于maven的web项目
2>. 本例源码下载地址: https://github.com/zhangbeizhen/spring-mybatis
2.创建基于maven的web项目
3.pom.xml配置
引入mybatis,druid,mysql-connector-java,spring,spring-web等模块
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zbz</groupId>
<artifactId>spring-mybatis</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>spring-mybatis Maven Webapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>nexus-aliyun</id>
<name>nexus Repository</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</repository>
</repositories>
<!-- 项目属性 -->
<properties>
<!-- 文件拷贝时的编码 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- 编译时的编码 -->
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<spring.version>4.3.14.RELEASE</spring.version>
<druid.version>1.1.0</druid.version>
<mybatis.version>3.4.4</mybatis.version>
<mybatis-spring.version>1.3.1</mybatis-spring.version>
<mysql.version>5.1.39</mysql.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.19</slf4j.version>
<fileupload.version>1.3.1</fileupload.version>
<commons-io.version>2.5</commons-io.version>
<commons.lang.version>2.6</commons.lang.version>
<commons.io.version>2.5</commons.io.version>
<commons.configuration.version>1.10</commons.configuration.version>
<fastjson.version>1.2.31</fastjson.version>
</properties>
<dependencies>
<!--mybatis begin -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!--mybatis end -->
<!-- mysql-Druid start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!-- mysql-Druid end -->
<!-- Spring begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Spring end -->
<!-- Spring MVC begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<!-- Spring MVC end -->
<!-- commons begin -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.4.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-discovery/commons-discovery -->
<dependency>
<groupId>commons-discovery</groupId>
<artifactId>commons-discovery</artifactId>
<version>0.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>${commons.configuration.version}</version>
</dependency>
<!-- commons end -->
<!-- jackson start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.9.2</version>
</dependency>
<!-- jackson end -->
<!-- Log begin -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- Log end -->
<!-- jsp-jstl-servlet start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>compile</scope>
</dependency>
<!-- jsp-jstl-servlet end -->
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
<version>1.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mybatis</finalName>
</build>
</project>
4.web.xml配置
1>.配置Log4j
2>.配置监听器
3>.配置加载spring配置文件
4>.配置SpringMVC分发器
5>.设置字符编码方式
6>.配置连接池启用Web监控统计
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 2019-3-15-->
<!-- 项目名称 -->
<display-name>spring-mybatis</display-name>
<!-- 配置Log4j -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置后可以获取客户端地址 -->
<!-- 监听HTTP请求事件,Web服务器接收的每次请求都会通知该监听器2018-12-28 -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- 加载spring配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/common/*.xml;WEB-INF/classes/jdbc/*.xml</param-value>
</context-param>
<!-- 配置SpringMVC分发器,拦截所有请求 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/mvc/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>
<!-- 设置字符编码方式 -->
<filter>
<filter-name>setencoding</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>
</filter>
<filter-mapping>
<filter-name>setencoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--连接池启用Web监控统计功能start -->
<filter>
<filter-name>DruidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>DruidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<!--连接池启用Web监控统计功能end -->
</web-app>
5.spring的基本配置与数据源配置
1>.在resources目录下创建如下目录与文件
/resources/common/spring-context.xml
/resources/common/application.properties
/resources/mvc/spring-mvc.xml
/resources/jdbc/spring-context-jdbc.xml
/resources/log4j.properties
<1>.spring-context.xml配置spring基本信息
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 2018-12-28 -->
<!-- 以上引入名称空间:spring容器根据名称空间寻找对应模块,相当于引入模块 -->
<!--引入注解驱动 -->
<mvc:annotation-driven />
<!-- 扫描包:扫描该包下所有模块 -->
<context:component-scan base-package="com.zbz" />
<!-- 配置线程池,参数 -->
<bean id="threadPoolTaskExecutor" name="threadPoolTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 线程池维护线程的最少数量 -->
<property name="corePoolSize" value="${executor.corePoolSize}" />
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="${executor.keepAliveSeconds}" />
<!-- 线程池维护线程的最大数量 -->
<property name="maxPoolSize" value="${executor.maxPoolSize}" />
<!-- 线程池所使用的缓冲队列 -->
<property name="queueCapacity" value="${executor.queueCapacity}" />
<!-- 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 ,调用者的线程会执行该任务,如果执行器已关闭,则丢弃. -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
</property>
<!-- 注意: ${executor.corePoolSize} 这些从配置文件ForPlatformconfig.properties获取 -->
</bean>
<!-- 引入 restTemplate模板操作类,使用时即可自动导入-->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate" />
<!-- 配置属性文件密码字符加密解密 application.properties -->
<bean id="config" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/classes/common/application.properties</value>
</list>
</property>
</bean>
</beans>
<2>.application.properties配置数据源参数
#配置线程池相关参数
executor.corePoolSize=18
executor.keepAliveSeconds=200
executor.maxPoolSize=60
executor.queueCapacity=3000
#zbz
zbz.url=jdbc:mysql://127.0.0.1:3306/zbzdb?useUnicode=true&characterEncoding=UTF-8
zbz.username=root
zbz.password=123456
zbz.driver=com.mysql.jdbc.Driver
<3>.spring-mvc.xml配置springmvc相关基本信息
<?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:p="http://www.springframework.org/schema/p"
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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 2019-3-15 -->
<!-- 扫描包 -->
<context:component-scan base-package="com.zbz"
use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!-- 对静态资源文件的访问,将无法mapping到Controller的path交给default servlet handler处理 -->
<mvc:default-servlet-handler />
<!-- 定义视图文件解析 2019-1-29 从配置文件获取值 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 默认的注解映射的支持,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -->
<mvc:annotation-driven
content-negotiation-manager="contentNegotiationManager">
<mvc:message-converters register-defaults="true">
<!-- 将StringHttpMessageConverter的默认编码设为UTF-8 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" />
</bean>
<!-- 将Jackson2HttpMessageConverter的默认格式化输出为false -->
<bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<!-- <property name="objectMapper">
<bean class="com.tl.config.CustomObjectMapper"></bean>
</property> -->
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- REST中根据URL后缀自动判定Content-Type及相应的View -->
<bean id="contentNegotiationManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml" />
<entry key="json" value="application/json" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<property name="favorPathExtension" value="true" />
</bean>
</beans>
<4>.spring-context-jdbc.xml配置spring与jdbc集成的基本信息
<?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-3.0.xsd">
<!-- 2018-12-28 -->
<!-- 配置数据库连接池 -->
<bean id="zbzDatasource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="driverClassName" value="${zbz.driver}" />
<property name="url" value="${zbz.url}" />
<property name="username" value="${zbz.username}" />
<property name="password" value="${zbz.password}" />
<property name="filters" value="stat" />
<property name="maxActive" value="20" />
<property name="initialSize" value="1" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
</bean>
<!-- 配置数据库事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="zbzDatasource" />
</bean>
<!-- 配置数据库事务模板 -->
<bean id="transactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager" />
</bean>
<!-- 配置数据jdbc模板 :在代码中可以直接注入使用即可 -->
<bean id="jtZbz" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="zbzDatasource" />
</bean>
</beans>
<5>.log4j.properties配置日志基本信息
### 父日志###
log4j.rootLogger=info,stdout
### 日志打印到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d{ISO8601}]:%5p %c{1}:%L - %m%n
### 日志写入文件 ###
log4j.appender.study=org.apache.log4j.DailyRollingFileAppender
log4j.appender.study.File=/home/admin/logs/spring-mybatis/spring-mybatis.log
log4j.appender.study.layout=org.apache.log4j.PatternLayout
log4j.appender.study.layout.ConversionPattern=[%d{ISO8601}] spring-mybatis \:%-5p %-x %X{user} %n %m%n
### 设置日志输出级别 ###
log4j.logger.org.springframework=info
log4j.logger.org.apache.cxf=info
log4j.logger.com.zbz=info,spring-mybatis
6.配置mybaits相关配置
1>在resources目录下创建如下目录与文件配置spring与mybatis关联
common/spring-context-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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- 本配置文件值包含spring集成mybatis的部分 2019-2-26 -->
<mvc:annotation-driven />
<!-- MyBatis begin -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="zbzDatasource" />
<property name="typeAliasesPackage" value="com.zbz.bean" />
<property name="mapperLocations" value="classpath:/mybatis/mapper/**/*.xml" />
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"></property>
</bean>
<!-- 扫描basePackage接口 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.zbz.mapper" />
</bean>
<!-- 定义事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="zbzDatasource" />
</bean>
<!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<!-- MyBatis end -->
</beans>
2>.在resources目录下创建如下目录与文件
/resources/mybatis/mapper/EmployeeMapper.xml
/resources/mybatis/mybatis-config.xml
<1>.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>
<!-- 开启驼峰命名 读取数据库字段自动映射到对象 2019-3-14 -->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
<2>.EmployeeMapper.xml信息
本例中EmployeeMapper.xml是Employee实例对应的增删改查sql
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zbz.mapper.EmployeeMapper">
<!-- 自动生成主键返回-->
<insert id="insertEmployee" useGeneratedKeys="true" keyProperty="id">
INSERT INTO employee(last_name,email,gender,card_number,post,department_id)
VALUES (#{lastName},#{email},#{gender},#{cardNumber},#{post},#{departmentId})
</insert>
<select id="getEmployeeById" resultType="com.zbz.bean.Employee">
SELECT * FROM employee WHERE id=#{id}
</select>
<update id="updateEmployee">
UPDATE employee SET
last_name=#{lastName},
email=#{email},
gender=#{gender},
card_number=#{cardNumber},
post=#{post},
department_id=#{departmentId}
WHERE id=#{id}
</update>
<delete id="deleteEmployeeById">
DELETE FROM employee WHERE id = #{id}
</delete>
</mapper>
7.与EmployeeMapper.xml映射接口类
@Mapper
public interface EmployeeMapper {
public int insertEmployee(Employee employee);
public Employee getEmployeeById(Integer id);
public int updateEmployee(Employee employee);
public int deleteEmployeeById(Integer id);
}
8.服务类
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**增*/
public Employee insertEmployee(Employee employee) {
System.out.println("插入数据");
employeeMapper.insertEmployee(employee);
return employee;
}
/**查*/
public Employee getEmployee( Integer id) {
Employee employee = employeeMapper.getEmployeeById(id);
return employee;
}
/**改*/
public Employee updateEmployee(Employee employee) {
int result = employeeMapper.updateEmployee(employee);
Employee employee1 = employeeMapper.getEmployeeById(employee.getId());
return employee1;
}
/**删*/
public Employee deleteEmployee(Integer id) {
employeeMapper.deleteEmployeeById(id);
return null;
}
}
9.controller类
@RestController
@RequestMapping("/emp")
public class EmployeeController {
@Autowired
EmployeeService employeeService;
/**增*/
@GetMapping("/insert")
public Employee insertEmployee(Employee employee) {
employeeService.insertEmployee(employee);
return employee;
}
/**
* 查
*/
@GetMapping("/query/{id}")
public Employee getEmployee(@PathVariable("id") Integer id) {
Employee employee = employeeService.getEmployee(id);
return employee;
}
/**改*/
@GetMapping("/update")
public Employee updateEmployee(Employee employee) {
Employee employee1 = employeeService.updateEmployee(employee);
return employee1;
}
/**删*/
@GetMapping("/delete/{id}")
public Employee deleteEmployee(@PathVariable("id") Integer id) {
employeeService.deleteEmployee(id);
return new Employee();
}
}
10.实体类
public class Employee implements Serializable {
private Integer id;
private String lastName;
private String email;
private Integer gender;
private String cardNumber;
/** 岗位 */
private String post;
/** 数据库字段: department_id 开启驼峰命名后可以自动匹配*/
private Integer departmentId;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public String getCardNumber() {
return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getPost() {
return post;
}
public void setPost(String post) {
this.post = post;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
}
11.建表语句
drop table if exists employee;
CREATE TABLE `employee` (
`id` INT(16) NOT NULL AUTO_INCREMENT COMMENT '编号',
`last_name` VARCHAR(128) DEFAULT NULL COMMENT '姓名',
`email` VARCHAR(128) DEFAULT NULL COMMENT '邮件',
`gender` INT(2) DEFAULT NULL COMMENT '性别',
`card_number` VARCHAR(64) DEFAULT NULL COMMENT '胸卡编号',
`post` VARCHAR(128) DEFAULT NULL COMMENT '岗位',
`department_id` INT(11) DEFAULT NULL COMMENT '部门编号',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COMMENT='员工表' ;
12.测试url:
http://127.0.0.1:8080/spring-mybatis/emp/insert?lastName=赵七&email=zhaoqi@163.com&gender=1&cardNumber=20190314002&post=程序猿&departmentId=1
http://127.0.0.1:8080/spring-mybatis/emp/query/2
http://127.0.0.1:8080/spring-mybatis/emp/update?id=1&lastName=王五&email=wangwu@163.com&gender=1&cardNumber=20190001&post=程序猿&departmentId=1
http://127.0.0.1:8080/spring-mybatis/emp/delete/2
以上,TKS.