MyBatis+Spring+SpringMVC
整合思想
SpringMVC主要负责请求的转发和视图管理————表现层
Spring运用IOC和AOP思想实现业务对象管理————核心业务
Mybatis封装JDBC作为数据对象的持久化引擎————数据库交互
一、环境搭建
- IDEA
- MySQL 5.7.19
- Tomcat 9
- Maven 3.6
1. 创建数据库
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
CREATE TABLE `books` (
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID` (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢')
2. 创建SSM的maven项目 添加web支持 导入依赖
<dependencies>
<!--Servlet 依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--Jsp 依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!--JSTL表达式-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--JUIT测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- 数据库连接池 -->
<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.5.2</version>
</dependency>
<!--Spring整合Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Spring-webmvc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--Spring-jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--注解实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
</dependencies>
<!--静态资源过滤-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3. 建包
dao pojo service controller
4. 导入配置文件
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>
</configuration>
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
Spring-dao.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">
二、Mybatis层
持久层:编写sql语句
1. 数据库配置文件 database.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=zy123456
2. IDEA关联数据库
3. 编写MyBatis的核心配置文件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>
<!--起别名-->
<typeAliases>
<package name="zy.pojo"/>
</typeAliases>
</configuration>
4. 编写pojo实体类books
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
5. 编写dao层功能接口BookMapper
// 增加
int addBook(Books books);
// 根据ID删除
int deleteBookByID(@Param("bookID")int bookID);
// 修改
int updateBook(Books books);
// 根据书名查询
Books selectBookByName(@Param("bookName")String bookName);
// 根据书名模糊查询
List<Books> selectBookLikeName(@Param("bookName")String bookName);
// 查询所有
List<Books> selectBookAll();
6. 编写dao层BookMapper.xml
<?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="zy.dao.BookMapper">
<!--增加-->
<insert id="addBook" parameterType="Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--删除-->
<delete id="deleteBookByID" parameterType="int">
delete from ssmbuild.books where bookID = #{bookID}
</delete>
<!--修改-->
<update id="updateBook" parameterType="Books">
update ssmbuild.books
set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail}
where bookID = #{bookID}
</update>
<!--根据书名查询-->
<select id="selectBookByName" resultType="Books">
select bookID,bookName,bookCounts,detail from ssmbuild.books
where bookName = #{bookName}
</select>
<!--根据书名模糊查询-->
<select id="selectBookLikeName" resultType="Books">
select bookID,bookName,bookCounts,detail from ssmbuild.books
where bookName like #{bookName}
</select>
<!--查询所有-->
<select id="selectBookAll" resultType="Books">
select bookID,bookName,bookCounts,detail from ssmbuild.books
</select>
</mapper>
7. 在MyBatis-Config.xml中绑定BookMapper.xml
<!--绑定Mapper-->
<mappers>
<mapper class="zy.dao.BookMapper"/>
</mappers>
8. 编写service层BookService
-
- 与BookMapper接口一致(去掉@Param)
9. 编写service层BookServiceImpl
// 调用dao层 set注入
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookByID(int bookID) {
return bookMapper.deleteBookByID(bookID);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books selectBookByName(String bookName) {
return bookMapper.selectBookByName(bookName);
}
public List<Books> selectBookLikeName(String bookName) {
return bookMapper.selectBookLikeName(bookName);
}
public List<Books> selectBookAll() {
return bookMapper.selectBookAll();
}
三、Spring层
1. 编写Spring-dao.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">
<!--1. 关联数据库db.properties-->
<context:property-placeholder location="classpath:db.properties"/>
<!--2. 数据库连接池c3p0-->
<bean id="dataSource" 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>
<!--3. 管理SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置MyBatis-Config.xml文件-->
<property name="configLocation" value="classpath:MyBatis-Config.xml"/>
</bean>
<!--4. 配置扫描Dao接口包,实现接口动态注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--需要扫描的Dao层的接口 作用:不用实现类注入,而是通过反射-->
<property name="basePackage" value="zy.dao"/>
</bean>
</beans>
Spring整合Mybatis:编写实现类,在实现类中注入sqlsessionfactory
spring-dao.xml中
<!--创建sqlsession 即Spring中的SqlSessionTemplate-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
applicationContext.xml中
<!--注入UserMapper实现类-->
<bean id="usermapper" class="zy.mapper.UserMapperImpl">
<property name="sqlSession" ref="sqlSession"/>
</bean>
SSM整合:内部自带扫描接口类,不用编写实现类,只用在bean中注入sqlsessionFactory
<!--4. 配置扫描Dao接口包,实现接口动态注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--需要扫描的Dao层的接口 作用:不用实现类注入,而是通过反射-->
<property name="basePackage" value="zy.dao"/>
</bean>
2. 编写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">
<!--1. 扫描service包下的注解-->
<context:component-scan base-package="zy.service"/>
<!--2. 手动注入实现类 也可用@Service和@Autowired注解自动注入-->
<bean name="bookServiceImpl" class="zy.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!--3. 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource" />
</bean>
</beans>
四、SpringMVC层
1. 编写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
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">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--扫描包下所有注解-->
<context:component-scan base-package="zy.controller"/>
<!--过滤:使得SpringMVC不处理静态资源 eg:html css-->
<mvc:default-servlet-handler/>
<!--装配InternalResourceViewResolver———————视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
2. 编写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">
<!--配置前端处理器,也是中央处理器-->
<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:ApplicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--SpringMVC自带的字符集编码过滤器-->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--设置Session过期时间-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
实现业务逻辑
1. controller业务
@Controller
public class BookController {
@Autowired
BookService bookService;
// 查询所有
@RequestMapping("/s1")
public String getAllBooks(Model model){
List<Books> bookList = bookService.selectBookAll();
model.addAttribute("booklist",bookList);
return "AllBooks";
}
// 模糊查询
@RequestMapping("/s2")
public String getBookByName(Model model,String bookName){
List<Books> booklist = bookService.selectBookLikeName("%" + bookName + "%");
model.addAttribute("booklist",booklist);
return "book";
}
// 跳转到新增页面
@RequestMapping("/a0")
public String toAddBook(){
return "addBook";
}
//新增书籍
@RequestMapping("/a1")
public String addBook(Books books){
bookService.addBook(books);
return "redirect:/s1";
}
//跳转到修改书籍
@RequestMapping("/u0")
public String toUpdateBook(String bookName,Model model){
Books book = bookService.selectBookByName(bookName);
model.addAttribute("book",book);
return "updateBook";
}
//修改书籍
@RequestMapping("/u1")
public String updateBook(Books book){
bookService.updateBook(book);
return "redirect:/s1";
}
//删除书籍
@RequestMapping("/d1")
public String deleteBook(int bookID){
bookService.deleteBookByID(bookID);
return "redirect:/s1";
}
}
2. 页面显示
全部书籍
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>书单</title>
<style>
th{
text-align:center;
height: 35px;
}
a {
text-decoration: none;
}
</style>
</head>
<body align="center">
<h1 align="center">书籍清单</h1>
<hr>
<button><a href="${pageContext.request.contextPath}/a0">新增书籍</a></button>
<form action="${pageContext.request.contextPath}/s2">
<input type="text" placeholder="请输入搜索的书籍" name="bookName">
<input type="submit" value="搜索">
</form>
<hr>
<table class="tab" border="2px" width="600px" align="center">
<tr>
<th>序列号</th>
<th>书名</th>
<th>数量</th>
<th>介绍</th>
<th>操作</th>
</tr>
<c:forEach var="booklist" items="${booklist}">
<tr>
<th> ${booklist.bookID}</th>
<th> ${booklist.bookName}</th>
<th> ${booklist.bookCounts}</th>
<th> ${booklist.detail}</th>
<th>
<a href="/u0?bookName=${booklist.bookName}">修改</a>
|
<a href="/d1?bookID=${booklist.bookID}">删除</a>
</th>
</tr>
</c:forEach>
</table>
</body>
</html>
新增书籍
<body>
<h1 align="center" style="color: royalblue;">书籍入库</h1>
<form action="${pageContext.request.contextPath}/a1" method="post">
<table align="center" bgcolor="#ffb6c1">
<tr><td>书名</td><td><input type="text" name="bookName"></td></tr>
<tr><td>数量</td><td><input type="text" name="bookCounts"></td></tr>
<tr><td>介绍</td><td><input type="text" name="detail"></td></tr>
<tr align="center">
<td colspan="1"><input type="submit" value="添加入库"></td>
<td><input type = "reset"></td>
</tr>
</table>
</form>
</body>
模糊查询书籍
%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>查询书籍</title>
<style>
th{
text-align:center;
height: 35px;
}
</style>
</head>
<body align="center">
<h1 align="center">指定书籍</h1>
<hr>
<table class="tab" border="2px" width="600px" align="center">
<tr>
<th>序列号</th>
<th>书名</th>
<th>数量</th>
<th>介绍</th>
<th>操作</th>
</tr>
<c:forEach var="booklist" items="${booklist}">
<tr>
<th> ${booklist.bookID}</th>
<th> ${booklist.bookName}</th>
<th> ${booklist.bookCounts}</th>
<th> ${booklist.detail}</th>
<th>
<a href="/u0?bookName=${booklist.bookName}">修改</a>
|
<a href="/d1?bookID=${booklist.bookID}">删除</a>
</th>
</tr>
</c:forEach>
</table>
</body>
</html>
修改书籍
<body align="center">
<h1 align="center" style="color: lightseagreen">书籍更正表</h1>
<form action="${pageContext.request.contextPath}/u1" method="post" align="center">
<table align="center" bgcolor="yellow">
<tr hidden><td hidden>序列号</td><td><input type="text" name="bookID" value="${book.bookID}" hidden></td></tr>
<tr><td>书名</td><td><input type="text" name="bookName" value="${book.bookName}"></td></tr>
<tr><td>数量</td><td><input type="text" name="bookCounts" value="${book.bookCounts}"></td></tr>
<tr><td>介绍</td><td><input type="text" name="detail" value="${book.detail}"></td></tr>
<tr align="center">
<td colspan="2"><input type="submit" value="修改"></td>
</tr>
</table>
</form>
</body>