此项目是结合springmvc和mybatis的整合,适合新手练习项目
1.编译环境及工具
- IDEA
- MySQL 8.0
- Tomcat 9
- Maven 4.0
2. 数据库表设计
CREATE DATABASE `ssmbuild`;
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
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,'从进门到进牢');
3.项目环境搭建
新建一个maven 的web项目,在pom.xml中导入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--Servlet - JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--spring - mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<!--mysql - 连接和数据源 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--mybatis和spring-mybatis - 整合-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
3.静态资源问题
在pom.xml文件中编写如下:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
4.创建基本项目结构
- pojo
- mapper
- service
- controller
- mybatis-config.xml
4.1 在pojo包下创建实体类(注意类属性和数据库字段同名)
package pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor // 无参
@AllArgsConstructor // 有参
public class MyBook {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
4.2 在mapper包下创建操作书籍的接口及对应的方法
4.2.1 Bookmapper接口
package mapper;
import org.apache.ibatis.annotations.Param;
import pojo.MyBook;
import java.util.List;
public interface Bookmapper {
//增加一个Book
int addBook(MyBook book);
//根据id删除一个Book
int deleteBookById(@Param("bookID") int id);
//更新Book
int updateBook(MyBook book);
//根据id查询,返回一个Book
MyBook queryBookById(@Param("bookID") int id);
//查询全部Book,返回list集合
List<MyBook> queryAllBook();
}
4.2.2 配置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.Bookmapper - 绑定Bookmapper -->
<mapper namespace="mapper.Bookmapper">
<!--增加一个Book-->
<insert id="addBook">
insert into books(bookName,bookCounts,detail)
values (#{bookName}, #{bookCounts}, #{detail})
</insert>
<!--根据id删除一个Book-->
<delete id="deleteBookById" >
delete from books where bookID=#{bookID}
</delete>
<!--更新Book-->
<update id="updateBook">
update books
set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
where bookID = #{bookID}
</update>
<!--根据id查询,返回一个MyBook 返回类型需要设置别名,如没有,默认为类的小写 -->
<select id="queryBookById" resultType="mybook">
select * from books
where bookID = #{bookID}
</select>
<!--查询全部Book-->
<select id="queryAllBook" resultType="mybook">
SELECT * from books
</select>
</mapper>
4.3 在service包下操作mapper接口和创建service实现类
4.3.1 BookService接口(其实就是Bookmapper接口的方法)
package service;
import pojo.MyBook;
import java.util.List;
public interface BookService {
//增加一个Book
int addBook(MyBook book);
//根据id删除一个Book
int deleteBookById(int id);
//更新Book
int updateBook(MyBook book);
//根据id查询,返回一个Book
MyBook queryBookById(int id);
//查询全部Book,返回list集合
List<MyBook> queryAllBook();
}
4.3.2 BookService实现类BookServiceImpl
package service;
import mapper.Bookmapper;
import pojo.MyBook;
import java.util.List;
public class BookServiceImpl implements BookService{
//调用dao层的操作,设置一个set接口,方便Spring管理
private Bookmapper bookMapper;
public void setBookMapper(Bookmapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(MyBook book) {
return bookMapper.addBook(book);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(MyBook books) {
return bookMapper.updateBook(books);
}
public MyBook queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<MyBook> queryAllBook() {
return bookMapper.queryAllBook();
}
}
4.4 配置mybatis-config.xml文件,并绑定mapper.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>
<typeAlias type="pojo.MyBook" alias="mybook"/>
</typeAliases>
<!--绑定mapper.xml-->
<mappers>
<!--通过class绑定mapper.xml-->
<mapper class="mapper.Bookmapper"/>
<!--通过resource绑定mapper.xml-->
<mapper resource="mapper/BookMapper.xml"/>
</mappers>
</configuration>
5.配置文件的编写
项目采用分开配置结构,便于spring容器管理
- db.properties 数据库的配置
- spring-mapper.xml dao配置操作数据库的 数据源(dataSource),数据配置文件,sqlSessionFactory 和相应的mapper扫描包
- spring-service.xml service 配置相应的service扫描包,配置事务管理
- spring-mvc.xml 配置controller扫描包 和视图解析器
- applicationContext.xml 整合mapper,service,mvc的全局配置文件
5.1 db.properties设置
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
# 注意不能写成username,在这里踩过坑
user=root
password=root
5.2 配置spring-mapper.xml
<!-- 配置整合mybatis -->
<!-- 1.关联数据库文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.数据库连接池 -->
<!--数据库连接池
dbcp 半自动化操作 不能自动连接
c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置连接池属性 -->
<property name="driverClass" value="${driver}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${password}"/>
<!-- c3p0连接池的私有属性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 关闭连接后不自动commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 获取连接超时时间 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 当获取连接失败重试次数 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
<!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="mapper"/>
</bean>
5.3 配置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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描service相关的bean -->
<context:component-scan base-package="service"/>
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="service.BookServiceImpl">
<property name="bookMapper" ref="bookmapper"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
5.4 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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.开启SpringMVC注解驱动 -->
<mvc:annotation-driven />
<!-- 2.静态资源默认servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 使用Jackson json解析器前段乱码问题解决-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!-- 4.扫描web相关的bean -->
<context:component-scan base-package="controller" />
</beans>
5.5 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
http://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="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
6 web.xml配置和controller的编写
6.1 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>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 需要全局配置文件applicationContext -->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--encodingFilter-->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
6.2 Bookcontroller配置
package controller;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.MyBook;
import service.BookService;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
@Qualifier(value = "BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<MyBook> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
@RequestMapping("/addBook")
public String addPaper(MyBook book) {
System.out.println(book);
bookService.addBook(book);
return "redirect:/book/allBook";
}
@RequestMapping("/toUpdateBook")
public String toupdateBook(Model model,int id) {
MyBook book = bookService.queryBookById(id);
System.out.println(book);
model.addAttribute("book",book);
return "updateBook";
}
@RequestMapping("/updateBook")
public String updateBook(Model model,MyBook book) {
System.out.println(book);
bookService.updateBook(book);
//MyBook books = bookService.queryBookById(book.getBookID());
model.addAttribute("books", book);
return "redirect:/book/allBook";
}
@RequestMapping("/del/{bId}")
public String deleteBook(@PathVariable("bId") int id) {
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
7. 遇到的坑
7.1 配置文件管理,否则bookmapper找不到
(
)
(
)
7.2 web.xml 配置的理应是全局文件
(
)
7.3 lib库没有导入
(
)
8.结果显示
(
)