SpringMvc整合Mybatis
SpringMvc整合Mybatis
配置案例
pom.xml
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!-- 版本锁定 -->
<spring.vesion>5.3.8</spring.vesion>
<log4j.vesion>1.2.17</log4j.vesion>
<mybatis.vesion>3.4.6</mybatis.vesion>
<mybatis-spring.vesion>2.0.6</mybatis-spring.vesion>
<mysql-connector.vesion>5.1.47</mysql-connector.vesion>
<c3p0.vesion>0.9.5.2</c3p0.vesion>
<lombok.vesion>1.18.8</lombok.vesion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.vesion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.vesion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.vesion}</version>
</dependency>
<!-- 据说这个是框架支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.vesion}</version>
</dependency>
<!--<dependency>-->
<!-- <groupId>commons-logging</groupId>-->
<!-- <artifactId>commons-logging</artifactId>-->
<!-- <version>1.2</version>-->
<!--</dependency>-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.vesion}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.vesion}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.vesion}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.vesion}</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>${c3p0.vesion}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.vesion}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<!-- 指定端口 -->
<port>82</port>
<!-- 请求路径 -->
<!--<path>/springmvc04</path>-->
<path>/</path>
<uriEncoding>UTF-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
web.xml
- 本文件的配置重点
spring
的配置使用context-param
进行导入,而spring-mvc
的配置使用前端控制器的初始化参数
的方式导入
- 其他的诸如还有在springmvc里面使用import方式导入spring和两个配置文件使用相同的前缀名使用通配符导入这里笔者都不建议,因为感觉体现不出来spring和springmvc是两个单独的ioc容器
<?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_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc配置 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
applicationContext.xml
- 本文件的配置重点
- 这是spring的配置文件,所以这里设置只扫描service注解的类进行实例化操作
- 这里按理来说应该是需要使用 exclude-filter 仅不扫描 controller 的,但是实际测试发现无法成功
- 下面mybatis-spring:scan 标签也报错
- 本文件配置了数据库连接池,事务管理等~
- 这是spring的配置文件,所以这里设置只扫描service注解的类进行实例化操作
<?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:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!--<import resource="classpath:springmvc.xml"/>-->
<!-- spring 管理所有的业务逻辑 -->
<context:component-scan base-package="link.rainful" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<!--<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>-->
</context:component-scan>
<!-- spring 用来控制业务逻辑、数据源、事务、aop等~! -->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="c3p0DataSource"/>
</bean>
<!-- 开启基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--
整合mybatis
目的: 管理所有mapper的实现类, 管理事务(声明式事务)
-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="c3p0DataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!-- 扫描所有的mapper -->
<!-- 老版配置 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="link.rainful.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>
</bean>
<!-- 新版配置然鹅idea报错 -->
<!--<mybatis-spring:scan base-package="link.rainful.mapper"/>-->
</beans>
springmvc.xml
- 本文件的配置重点
- 只扫描controller注解的类进行管理
- 设置视图解析器
- 设置默认资源处理(防止前端控制器拦截访问html等静态资源又无法处理报错404)
<?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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- springmvc 只是控制网站跳转逻辑 -->
<!--
雷神是建议让springmvc管controller,spring管别的,但是已知报错无法解决,
目前解决办法是spring不用ex用include
-->
<context:component-scan base-package="link.rainful" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--<context:component-scan base-package="link.rainful"/>-->
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:default-servlet-handler/>
</beans>
mybatis-config.xml
- 本文件配置重点
- 这个文件是mybatis原来的配置文件,但是大部分都交给spring管理了,这里只配置一些经常变化的设置
<?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>
<!--开启自动驼峰命名-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="LOG4J"/>
<!--全局开启缓存(默认就是true,但是为了反正版本变化默认值)-->
<!--<setting name="cacheEnabled" value="true"/>-->
</settings>
</configuration>
log4j.properties
- 本文件配置重点
- log4j的日志配置
#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/rainful.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
db.properties
- 本文件就是数据库的连接
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://ip:端口/xxx
jdbc.username=root
jdbc.password=
-
其他
-
数据库访问对象
@Data public class Employee { private Integer id; private String name; private String email; private String gender; private Integer departmentId; }
-
Mapper
public interface EmployeeMapper { /** * 根据id获取员工对象 * @param id 员工id * @return 员工对象 */ Employee getEmployeeById(@Param("id") Integer id); }
<?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="link.rainful.mapper.EmployeeMapper"> <!--Employee getEmployeeById(Integer id);--> <select id="getEmployeeById" parameterType="int" resultType="link.rainful.pojo.Employee"> select * from rainful_ssm_01.employess where id = #{id}; </select> </mapper>
-
Service
public interface EmployeeService { /** * 获取单个员工 * @param id * @return */ Employee getEmployeeById(Integer id); }
@Service public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeMapper employeeMapper; @Override public Employee getEmployeeById(Integer id) { return employeeMapper.getEmployeeById(id); } }
-
Controller
@Controller public class EmployeeController { @Autowired private EmployeeService employeeService; @RequestMapping("/emp/{id}") public String getEmp(@PathVariable Integer id){ System.out.println("getEmp运行"); System.out.println(employeeService.getEmployeeById(id)); return "success"; } }
-
index.jsp
-
success.jsp(WEB-INF下的pages文件夹里面放)
-