Mybatis层的创建
一、数据库的创建
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 '书名',
bookConunts INT(11) NOT NULL COMMENT '数量',
detail VARCHAR(200)NOT NULL COMMENT '描述',
KEY bookID(bookID)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO books(bookID,bookName,bookConunts,detail)VALUES
(1,'Java',1,'从入门到放弃'),
(2,'Mysql',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
二、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ssmbuild</artifactId>
<version>1.0-SNAPSHOT</version>
<!--依赖:junit,数据库驱动,连接池,servlet.jsp.mybatis.mybatis-spring-->
<dependencies>
<!-- junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.20</version>
</dependency>
<!-- 数据库连接池:c3p0-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- servlet-jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!-- spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!-- lombok 解决实体类中getter和setter代码影响美观问题-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
<!-- 静态资源导出问题-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory><!--所在的目录-->
<includes><!--包括目录下的.properties,.xml文件都会扫描到-->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
三、测试连接数据库
四、Spring核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!--spring核心配置文件-->
五、Mybatis核心配置文件
1、基础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>
<!--mybatis核心配置文件-->
</configuration>
2、database.properties
数据库连接
如果使用的是mysql8.0+,那么还需要增加一个时区的配置;
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
六、实体类创建
<!-- lombok 解决实体类中getter和setter代码影响美观问题-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
1、Books实体类
//加上@data后除了有参构造都有了
@Data
//但是加上有参构造后无参就没了,所以一般都加上三个
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookConunts;
private String detail;
}
2、dao层创建
2.1 BookMapper
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(Books books);
//查询全部书
List<Books> queryAllBook();
}
2.2 BookMapper.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">
<!--绑定接口-->
<mapper namespace="com.zuilizhehua.dao.BookMapper">
<insert id="addBook" parameterType="com.zuilizhehua.pojo.Books">
insert into ssmbuild.books(bookName,bookConunts,detail)
values(#{bookName},#{bookConunts},#{detail});
</insert>
<delete id="deleteBookById" parameterType="int">
delete from ssmbuild.books where bookID=#{bookId};
</delete>
<update id="updateBook" parameterType="com.zuilizhehua.pojo.Books">
update ssmbuild.books
set bookName=bookName=#{bookName},bookConunts=#{bookConunts},detail=#{detail}
where bookID=#{bookID}
</update>
<select id="queryBookById" resultType="com.zuilizhehua.pojo.Books">
select * from ssmbuild.books
where bookID=#{bookId};
</select>
<select id="queryAllBook" resultType="com.zuilizhehua.pojo.Books">
select * from ssmbuild.books;
</select>
</mapper>
去mybatis-config.xml中注册
<mappers>
<mapper class="com.zuilizhehua.dao.BookMapper"/>
</mappers>
3、业务层Service
3.1、BookService:
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBookById(int id);
//查询全部书
List<Books> queryAllBook();
}
3.2、BookServiceImpl
public class BookServiceImpl implements BookService{
//service层调dao层,组合dao层,对它进行托管
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
4.Controller
BookController:
@Controller
@RequestMapping("/book")
public class BookController {
//controller 调service层
//首先注入service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
//查询全部数据,并且返回到一个书籍展示页面
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list=bookService.queryAllBook();
model.addAttribute("list",list);
return "allBook";
}
//跳转到增加书籍页面
@RequestMapping("/toAddBook")
public String toAddPape(){
return "addBook";
}
//添加书籍的请求
@RequestMapping("/addBook")
public String addBook(Books books){
bookService.addBook(books);
return "redirect:/book/allBook";//重定向到我们的@RequestMapping("/allBook")请求;
}
//跳转到修改页面
@RequestMapping("/toUpdate")
public String toUpdatePaper(int id,Model model){
Books books=bookService.queryBookById(id);
model.addAttribute("queryBooks",books);
return "updateBook";
}
//修改书籍
@RequestMapping("/updateBook")
public String updateBook(Books books){
System.out.println("updateBooks=>"+books);
bookService.updateBook(books);
//跳转到的是上面的方法
return "redirect:/book/allBook";
}
//删除书籍
//restful风格
@RequestMapping("/deleteBook/{bookID}")
public String deleteBook(@PathVariable("bookID") int id){
int i=bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
}
Spring层的创建(大杂烩,整合dao和service)
一、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
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--spring核心配置文件-->
<!--1.关联数据库配置文件,写死的-->
<context:property-placeholder location="classpath:database.properties"/>
<!-- 2.连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作,自动化的加载配置文件,并且可以自动设置到对象中!
druid
hikari
-->
<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的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中(不用创建类继承然后定义sqlSessionFactory)-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 要扫描的dao包-->
<property name="basePackage" value="com.zuilizhehua.dao"/>
</bean>
</beans>
二、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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.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">
<!--1.扫描service下的包-->
<context:component-scan base-package="com.zuilizhehua.service"/>
<!-- 2.将我们的所有业务类,注入到spring,可以通过配置,或者注解实现-->
<bean id="BookServiceImpl" class="com.zuilizhehua.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 3.声明式事务配置,只需要配置数据源,如果要横切事务,还要配置aop的植入-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 4. aop横切事务支持-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.zuilizhehua.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
三、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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
MVC层的创建
一、添加web框架的支持
二、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">
<!-- 至少要配置两个东西,DispatchServlet和乱码过滤-->
<!-- DispatchServlet-->
<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:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 乱码过滤-->
<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>
<!-- Session-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
三、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 http://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<!--1.注解驱动-->
<mvc:annotation-driven/>
<!-- 2.静态资源过滤-->
<mvc:default-servlet-handler/>
<!-- 3.扫描包:controller-->
<context:component-scan base-package="com.zuilizhehua.controller"/>
<!-- 4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
以上就是要给spring整合好的业务底层,以后要用只需要网上添加业务就可以了。
前端页面(可以从bootStrap上使用前端页面样式)
一、allBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>书籍展示</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/book/toAddBook">添加书籍</a>
<a href="${pageContext.request.contextPath}/book/allBook">显示全部书籍</a>
<%--查询书籍--%>
<form action="${pageContext.request.contextPath}/book/queryBook" method="post">
<span style="color: red">${error}</span>
<input type="text" name="queryBookName" placeholder="请输入要查询的书籍名称">
<input type="submit" value="查询">
</form>
<h1>书籍展示</h1>
<table >
<thead>
<tr>
<th>书籍编号</th>
<th>书籍名称</th>
<th>书籍数量</th>
<th>书籍详情</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="book" items="${list}">
<tr>
<td>${book.bookID}</td>
<td>${book.bookName}</td>
<td>${book.bookConunts}</td>
<td>${book.detail}</td>
<td>
<%-- 修改瞬间要携带数据--%>
<a href="${pageContext.request.contextPath}/book/toUpdate?id=${book.bookID}">修改</a>
|
<a href="${pageContext.request.contextPath}/book/deleteBook/${book.bookID}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
二、addBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: 岁月如歌
Date: 2020/12/9
Time: 12:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/addBook" method="post">
<%-- 其中name属性的值必须和实体类相对应,否则会报错--%>
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control" required>
<label>书籍数量:</label>
<input type="text" name="bookConunts" class="form-control"required>
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control"required>
<input type="submit" class="form-control" value="添加">
</form>
</body>
</html>
三、updateBook.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>添加书籍</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book/updateBook" method="post">
<%-- 其中name属性的值必须和实体类相对应,否则会报错--%>
<input type="hidden" name="bookID" value="${queryBooks.bookID}">
<label>书籍名称:</label>
<input type="text" name="bookName" class="form-control" value="${queryBooks.bookName}" required>
<label>书籍数量:</label>
<input type="text" name="bookConunts" class="form-control" value="${queryBooks.bookConunts}" required>
<label>书籍描述:</label>
<input type="text" name="detail" class="form-control" value="${queryBooks.detail}" required>
<input type="submit" class="form-control" value="修改">
</form>
</body>
</html>
四、index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<h3>
<a href="${pageContext.request.contextPath}/book/allBook">跳转</a>
</h3>
</body>
</html>