整合Spring+Mybatis+SpringMVC
1. 导入目前需要的jar包(以后需要的再添加依赖)
1.1. maven依赖
<dependencies>
<!-- junit测试的包 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!-- spring 相关jar包,maven会进行依赖导入其余的 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- servlet 和 jsp 相关的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!--JSTL表达式依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--standard标签库-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!-- mysql连接数据库驱动的 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<!-- C3P0数据库连接池 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Mybatis 的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- Mybatis整合Spring的包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- spring操作数据库的包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.3.RELEASE</version>
</dependency>
</dependencies>
1.2. maven的静态资源过滤
<!-- maven静态资源过滤,否则java包的非java文件不会打包 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
2. 先写整体的架构,添加pojo(实体类层),dao层(与Mybatis整合的Mapper接口),service层(操作dao对数据库,主要是为了方便添加事务)
2.1. 接口BookStoreMapper
package com.xxx.dao;
import com.xxx.pojo.BookStore;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BookStoreMapper {
// 增加一本书
int addBook(BookStore bookStore);
// 根据ID 删除一本书
int deleteBook(@Param("bookID") int id);
// 修改一本书
int updateBook(BookStore bookStore);
// 根据ID 查询一本书
BookStore selectBookById(@Param("bookID") int id);
// 查询全部书
List<BookStore> selectBooks();
}
2.2. 实体类: BookStore.java
public class BookStore {
private int bookID;
private int bookCounts;
private String bookName;
private String detail;
// set get toString 构造方法
}
2.3. service层的接口加实现类
public interface BookStoreService {
// 增加一本书
int addBook(BookStore bookStore);
// 根据ID 删除一本书
int deleteBook(@Param("bookID") int id);
// 修改一本书
int updateBook(BookStore bookStore);
// 根据ID 查询一本书
BookStore selectBookById(@Param("bookID") int id);
// 查询全部书
List<BookStore> selectBooks();
}
public class BookStoreServiceImpl implements BookStoreService {
private BookStoreMapper bookStoreMapper;
// 通过set方法可以通过spring的property进行 注入
public void setBookStoreMapper(BookStoreMapper bookStoreMapper) {
this.bookStoreMapper = bookStoreMapper;
}
public int addBook(BookStore bookStore) {
return bookStoreMapper.addBook(bookStore);
}
public int deleteBook(int id) {
return bookStoreMapper.deleteBook(id);
}
public int updateBook(BookStore bookStore) {
return bookStoreMapper.updateBook(bookStore);
}
public BookStore selectBookById(int id) {
return bookStoreMapper.selectBookById(id);
}
public List<BookStore> selectBooks() {
return bookStoreMapper.selectBooks();
}
}
3. 写Mybatis的配置文件,mybatis-config.xml和Mapper.xml的映射文件
3.1. mybatis-config.xml(这里只写别名和映射文件xml,数据源使用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="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 起别名 (默认别名为 原来类名的首字母小写) -->
<typeAliases>
<package name="com.xxx.pojo"/>
</typeAliases>
<!-- 映射文件的 -->
<mappers>
<mapper resource="BookStoreMapper.xml"/>
</mappers>
</configuration>
3.2. Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace 选择映射接口的全限类名 -->
<mapper namespace="com.xxx.dao.BookStoreMapper">
<insert id="addBook" parameterType="bookStore">
insert into bookstore(bookCounts,bookName,detail)
values(#{bookCounts},#{bookName},#{detail})
</insert>
<update id="updateBook" parameterType="bookStore">
update bookstore set bookCounts=#{bookCounts},bookName=#{bookName},detail=#{detail}
where bookID=#{bookID}
</update>
<delete id="deleteBook" parameterType="int">
delete from bookstore where bookID=#{bookID}
</delete>
<select id="selectBookById" parameterType="int" resultType="bookStore">
select * from bookstore where bookID=#{bookID}
</select>
<select id="selectBookById" resultType="bookStore">
select * from bookstore
</select>
</mapper>
4. 将Mybatis整合进Spring
4.1. 编写spring-mybatis.xml(spring联合Mybatis操作数据库)的配置文件
<?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:mybatis="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd
">
<!-- 读取properties的配置文件 -->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 配置数据源 spring 自带的数据源-->
<!--<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
<!--<property name="driverClassName" value="${driver}"/>-->
<!--<property name="url" value="${url}"/>-->
<!--<property name="username" value="${name}"/>-->
<!--<property name="password" value="${pwd}"/>-->
<!--</bean>-->
<!-- 配置C3P0数据源 -->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${name}"/>
<property name="password" value="${pwd}"/>
</bean>
<!-- 创建sqlsessionFactory对象 -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 创建sqlsessionTemplate 对象 -->
<!--<bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">-->
<!--<constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!--</bean>-->
<!-- 动态扫描 dao层 生成接口的实现类 默认bean的id是 接口名首字母小写 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xxx.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<!-- 动态扫描 dao层 内部也需要sqlSessionFactory或者创建sqlsessionTemplate对象 -->
<!--<mybatis:scan base-package="com.xxx.dao"/>-->
</beans>
4.2. spring操作业务层:spring-service.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
// 动态扫描通过注解形式 生成Bean
<context:component-scan base-package="com.xxx.service"/>
<bean id="bkService" class="com.xxx.service.BookStoreServiceImpl">
<!-- 注入 通过接口动态生成的mapper对象,扫描的默认名称为类名首字母小写 -->
<property name="bookStoreMapper" ref="bookStoreMapper"/>
</bean>
</beans>
5. 将SpringMVC整合进Spring
5.1. 首先需要将项目变为web项目,配置 web.xml(前端调度器,乱码过滤器)
5.1.1. 前端调度器直接加载spring的主配置文件:
<?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_4_0.xsd"
version="4.0">
<!-- 前端调度器 -->
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 这里可以直接写 spring 的主配置文件 进行加载 -->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring自带的乱码过滤器 -->
<filter>
<filter-name>encodefilter</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>encodefilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
5.1.2. 前端调度器加载springmvc的配置文件,使用监听上下文ServletContext创建的监听器,其加载spring的主配置文件,这种方式是双亲上下文,即前端调度器的可以使用spring容器的对象(因为加载spring容器的Applicationcontext存在servletContext对象中,一个tomcat服务器共享一个,谁都可以拿到),Spring容器的无法使用springmvc容器的对象(springmvc的配置文件是单独加载的)
web.xml
<?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_4_0.xsd"
version="4.0">
<!-- 使用监听servletContext创建的监听器去加载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>
<!-- 前端调度器 -->
<servlet>
<servlet-name>dispatch</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--<param-value>classpath:applicationContext.xml</param-value>-->
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatch</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring自带的乱码过滤器 -->
<filter>
<filter-name>encodefilter</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>encodefilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 这里没有导入springmvc的配置文件 -->
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:spring-service.xml"/>
<!--<import resource="classpath:spring-mvc.xml"/>-->
</beans>
5.2. 编写SpringMVC的配置文件 spring-mvc.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://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
">
<!-- 映射处理器 -->
<!-- 处理器适配器 使用注解形式的 -->
<mvc:annotation-driven/>
<!-- 静态资源过滤器 -->
<mvc:default-servlet-handler/>
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 处理器 (包扫描) -->
<context:component-scan base-package="com.xxx.controller"/>
</beans>
6. 将所有的spring的配置文件导入到applicationContext.xml中
6.1. applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
">
<import resource="classpath:spring-mybatis.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
6.2. 整合后的结构图:
7. 测试程序
7.1. 编写Controller层的代码:
package com.xxx.controller;
import com.xxx.pojo.BookStore;
import com.xxx.service.BookStoreServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class testController {
@Autowired
private BookStoreServiceImpl service;
@RequestMapping("/show01")
public String show01(Model model){
List<BookStore> bookStores = service.selectBooks();
model.addAttribute("msg",bookStores);
return "test";
}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>test.jsp</h1>
<table border="1">
<tr>
<th>bookID</th>
<th>bookCounts</th>
<th>bookName</th>
<th>detail</th>
</tr>
<c:forEach items="${msg}" var="item">
<tr>
<td>${item.bookID}</td>
<td>${item.bookCounts}</td>
<td>${item.bookName}</td>
<td>${item.detail}</td>
</tr>
</c:forEach>
</table>
</body>
</html>