CREATE DATABASE `SSM`;
USE `SSM`;
DROP TABLE IF EXISTS `BOOKS`;
CREATE TABLE `BOOKS` (
`BOOK_ID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书ID',
`BOOK_NAME` VARCHAR(100) NOT NULL COMMENT '书名',
`BOOK_COUNTS` INT(11) NOT NULL COMMENT '数量',
`DETAIL` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `BOOK_ID` (`BOOK_ID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `BOOKS`(`BOOK_ID`,`BOOK_NAME`,`BOOK_COUNTS`,`DETAIL`)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.26version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.3version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.7version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.3.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.3.9version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.20version>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
配置文件名称 : applicationContext.xml
<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.xsd">
beans>
应用上下文关联了所有的 spring 配置文件,最好保证所有的配置文件都在其中。
配置文件名 : mybatis-config.xml
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
configuration>
配置路径:resources/com/why/dao/ mybatis-config.xml
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
settings>
配置路径:resources/com/why/dao/ mybatis-config.xml
<typeAliases>
<package name="com.why.pojo"/>
typeAliases>
package com.why.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* TODO
* Books 实体类
* @author why
* @since 2021/9/16 10:59
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Books {
private Integer bookId;
private String bookName;
private Integer bookCounts;
private String detail;
}
package com.why.dao;
import com.why.pojo.Books;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* TODO
* Book 映射器
* @author why
* @since 2021/9/16 13:20
*/
public interface BookMapper {
/**
* 增加一本书
* @param book Books 对象
* @return Integer 结果
*/
Integer addBook(Books book);
/**
* 根据书 ID 删除一本书
* @param id 书 ID
* @return Integer 结果
*/
Integer deleteBookById(@Param("bookId") Integer id);
/**
* 更新一本书
* @param book Books 对象
* @return Integer 结果
*/
Integer updateBook(Books book);
/**
* 根据书 ID 查询一本书
* @param id 书 ID
* @return Books 结果
*/
Books queryBookById(@Param("bookId") Integer id);
/**
* 查询全部书
* @return List 结果
*/
List<Books> queryAllBook();
}
xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.why.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into ssm.books (BOOK_NAME, BOOK_COUNTS, DETAIL) values (#{bookName}, #{bookCounts}, #{detail});
insert>
<delete id="deleteBookById" parameterType="int">
delete from ssm.books where BOOK_ID = #{bookId};
delete>
<update id="updateBook" parameterType="Books">
update ssm.books
set BOOK_NAME = #{bookName}, BOOK_COUNTS = #{bookCounts}, DETAIL = #{detail}
where BOOK_ID = #{bookId};
update>
<select id="queryBookById" resultType="Books">
select * from ssm.books where BOOK_ID = #{bookId};
select>
<select id="queryAllBook" resultType="Books">
select * from ssm.books;
select>
mapper>
注册路径:resources/com/why/dao/ mybatis-config.xml
<mappers>
<mapper class="com.why.dao.BookMapper"/>
mappers>
package com.why.service;
import com.why.pojo.Books;
import java.util.List;
/**
* TODO
* Book 服务接口
* @author why
* @since 2021/9/16 14:03
*/
public interface BookService {
/**
* 增加一本书
* @param book Books 对象
* @return Integer 结果
*/
Integer addBook(Books book);
/**
* 根据书 ID 删除一本书
* @param id 书 ID
* @return Integer 结果
*/
Integer deleteBookById(Integer id);
/**
* 更新一本书
* @param book Books 对象
* @return Integer 结果
*/
Integer updateBook(Books book);
/**
* 根据书 ID 查询一本书
* @param id 书 ID
* @return Books 结果
*/
Books queryBookById(Integer id);
/**
* 查询全部书
* @return List 结果
*/
List<Books> queryAllBook();
}
package com.why.service.Impl;
import com.why.dao.BookMapper;
import com.why.pojo.Books;
import com.why.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* TODO
* Book 服务实现类
* @author why
* @since 2021/9/16 14:05
*/
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public Integer addBook(Books book) {
return bookMapper.addBook(book);
}
public Integer deleteBookById(Integer id) {
return bookMapper.deleteBookById(id);
}
public Integer updateBook(Books book) {
return bookMapper.updateBook(book);
}
public Books queryBookById(Integer id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
jdbc.driver=com.mysql.jdbc.Driver
# MySQL 8.0+ 需配置时区:&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssm?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=981030
<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.xsd">
beans>
引入 context 约束
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
此处也可用 IDEA 自动引入,但引入的为 c 空间和 p 空间约束,编写代码无提示。
配置数据库配置文件路径
<context:property-placeholder location="classpath:database.properties"/>
<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}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
此处配置可理解为由 Spring 完成 Mybatis 中 getSqlSession 操作
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.why.dao"/>
bean>
applicationContext.xml
引入路径:resources/ applicationContext.xml
<import resource="classpath:spring-dao.xml"/>
<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.xsd">
beans>
<context:component-scan base-package="com.why.service"/>
<bean id="bookMapperImpl" class="com.why.service.impl.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
bean>
//注解实现:
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
...
}
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
applicationContext.xml
引入路径:resources/ applicationContext.xml
<import resource="classpath:spring-service.xml"/>
package com.why;
import com.why.pojo.Books;
import com.why.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
/**
* TODO
* 测试类
* @author why
* @since 2021/9/16 20:12
*/
public class MyTest {
@Test
public void testAllBooks() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println(context);
BookService bookService = (BookService) context.getBean("bookServiceImpl");
System.out.println(bookService);
List<Books> books = bookService.queryAllBook();
for (Books book : books) {
System.out.println(book);
}
}
}
Mybatis 整合完毕!!!
<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.xsd">
beans>
xmlns:mvc="http://www.springframework.org/schema/mvc"
...
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
xmlns:context="http://www.springframework.org/schema/context"
...
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
controller
包
<context:component-scan base-package="com.why.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
applicationContext.xml
引入路径:resources/ `applicationContext.xml
<import resource="classpath:spring-mvc.xml"/>
web.xml
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
index.jsp
<%--
User: why
Date: 2021/9/16
Time: 17:03
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
首页
进入书籍页面
<%--
User: why
Date: 2021/9/16
Time: 20:02
--%>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
All Books
书籍列表
编号
数量
数量
详情
<%--items 的值是控制器中 model.addAttribute("books", books); 的关键字 "books" --%>
${book.bookId}
${book.bookName}
${book.bookCounts}
${book.detail}
package com.why.controller;
import com.why.pojo.Books;
import com.why.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* TODO
* Book 控制器
* @author why
* @since 2021/9/16 19:51
*/
@Controller
@RequestMapping("/book")
public class BookController {
// 自动装配
@Autowired
// 指定一个 bean (bookServiceImpl)为 bookService 属性进行装配,可省略
@Qualifier("bookServiceImpl")
private BookService bookService;
@RequestMapping("/allBooks")
public String allBooks(Model model) {
List<Books> books = bookService.queryAllBook();
model.addAttribute("books", books);
return "allBooks";
}
}
Spring MVC 整合完毕!!!
@RequestMapping("/toAddBook")
public String toAddBook() {
return "addBook";
}
<%--
Created by IntelliJ IDEA.
User: LENOVO
Date: 2021/9/17
Time: 19:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Add Book
添加书籍
@RequestMapping("/addBook")
public String addBook(Books book) {
System.out.println("addBook.book => "+book);
Integer addRes = bookService.addBook(book);
System.out.println("addRes => " + addRes);
return "redirect:/book/allBooks";
}
操作
...
<%--删除--%>
@RequestMapping("/deleteBook/{id}")
public String deleteBook(@PathVariable("id") Integer id) {
Integer deleteRes = bookService.deleteBookById(id);
System.out.println("deleteRes => " + deleteRes);
return "redirect:/book/allBooks";
}
<%--修改--%>
@RequestMapping("/toUpdate")
public String toUpdate(Integer id, Model model) {
Books book = bookService.queryBookById(id);
System.out.println("toUpdate.book => "+book);
model.addAttribute("book", book);
return "updateBook";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Update Book
修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books book) {
System.out.println("updateBook.book => "+book);
Integer updateRes = bookService.updateBook(book);
System.out.println("updateRes => " + updateRes);
return "redirect:/book/allBooks";
}
...
<%--警告提示框--%>
×
${error}
<%--关闭警告框--%>
@RequestMapping("/queryBookByName")
public String queryBookByName(String name, Model model) {
System.out.println("queryBookByName.name => " + name);
if (name == null || name.equals("")) {
return "redirect:/book/allBooks";
}
List<Books> books = bookService.queryBookByName(name);
System.out.println("queryBookByName.books.size => " + books.size());
if (books.size() == 0) {
String error = "警告!没有查询到此书籍。";
model.addAttribute("error", error);
books = bookService.queryAllBook();
}
model.addAttribute("books", books);
return "allBooks";
}