SSM(Spring+SpringMVC+MyBatis)整合+CRUD【IDEA版】
1.导入数据库
- 以下数据与实际不符,仅用于测试
drop database if exists ssm; create database ssm; use ssm; ##创建图书表 create table t_book( `id` int(11) primary key auto_increment, ## 主键 `name` varchar(50) not null, ## 书名 `author` varchar(50) not null, ## 作者 `price` decimal(11,2) not null, ## 价格 `sales` int(11) not null, ## 销量 `stock` int(11) ## 库存 ); ## 插入初始化测试数据 insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '平凡的世界' , '路遥' , 80 , 9999 , 9 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '如何阅读一本书' , '莫提默·J. 艾德勒' , 78.5 , 6 , 13 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '月亮与六便士' , '毛姆' , 68, 99999 , 52 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '白夜行' , '东野圭吾' , 16, 1000 , 50 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , 'Java编程思想' , '埃克尔' , 45.5 , 14 , 95 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '三体' , '刘慈欣' , 9.9, 12 , 53 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '龙族' , '江南' , 66.5, 125 , 535 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '简爱' , '夏洛蒂·勃朗特' , 99.5 , 47 , 36 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '大话设计模式' , '吴强' , 89.15 , 20 , 10 ); insert into t_book(`id` , `name` , `author` , `price` , `sales` , `stock`) values(null , '人月神话' , '布鲁克斯' , 88.15 , 20 , 80 ); ## 查看表内容 select id,name,author,price,sales,stock from t_book;
2.创建web项目
3.导入相关jar包
(1)在web项目的web-inf目录下,创建libs文件夹,用于存放jar包
(2)将jar包添加到项目中
4.将项目部署到 tomcat
- 启动tomcat,进行测试
- 如果启动不成功时,可以build一下,重新构建模块
5.使用MBG,生成相关的mybatis代码
(1)MBG配置文件
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 6 <generatorConfiguration> 7 8 <context id="DB2Tables" targetRuntime="MyBatis3"> 9 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 10 connectionURL="jdbc:mysql://localhost:3306/ssm" 11 userId="root" 12 password="admin"> 13 </jdbcConnection> 14 15 <javaTypeResolver > 16 <property name="forceBigDecimals" value="false" /> 17 </javaTypeResolver> 18 19 <javaModelGenerator targetPackage="fun.jiayou.pojo" targetProject=".\src"> 20 <property name="enableSubPackages" value="true" /> 21 <property name="trimStrings" value="true" /> 22 </javaModelGenerator> 23 24 <sqlMapGenerator targetPackage="fun.jiayou.mapper" targetProject=".\src"> 25 <property name="enableSubPackages" value="true" /> 26 </sqlMapGenerator> 27 28 <javaClientGenerator type="XMLMAPPER" targetPackage="fun.jiayou.mapper" targetProject=".\src"> 29 <property name="enableSubPackages" value="true" /> 30 </javaClientGenerator> 31 32 <table tableName="t_book" domainObjectName="Book" ></table> 33 34 </context> 35 </generatorConfiguration>
(2)生成类
1 public class Create { 2 public static void main(String[] args) throws Exception { 3 List<String> warnings = new ArrayList<String>(); 4 boolean overwrite = true; 5 File configFile = new File("./src/mbg-config.xml"); 6 ConfigurationParser cp = new ConfigurationParser(warnings); 7 Configuration config = cp.parseConfiguration(configFile); 8 DefaultShellCallback callback = new DefaultShellCallback(overwrite); 9 MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); 10 myBatisGenerator.generate(null); 11 } 12 }
(3)添加log.properties配置文件
1 log4j.rootLogger=DEBUG, stdout 2 3 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 log4j.appender.stdout.layout.ConversionPattern=%c{1} - %m%n 6 7 log4j.logger.java.sql.PreparedStatement=DEBUG
(4)编译Create类
(5)生成完成
6.整合mybatis+spring
(1)创建mybatis-config.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 8 <settings> 9 <!-- 打开延迟加载的开关 --> 10 <setting name="lazyLoadingEnabled" value="true" /> 11 <!-- 将积极加载改为消极加载 按需加载 --> 12 <setting name="aggressiveLazyLoading" value="false"/> 13 <!-- 开启自动驼峰命名规则,将数据库字段名a_column映射为javabean的aColumn --> 14 <setting name="mapUnderscoreToCamelCase" value="true"/> 15 <!-- 开启二级缓存--> 16 <setting name="cacheEnabled" value="true"/> 17 </settings> 18 19 <!--添加分页插件--> 20 <plugins> 21 <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> 22 </plugins> 23 24 </configuration>
(2)创建spring-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:tx="http://www.springframework.org/schema/tx" 6 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://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 7 8 <!--开启注解扫描--> 9 <context:component-scan base-package="fun.jiayou"> 10 <!--排除扫描controller--> 11 <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 12 </context:component-scan> 13 14 <!--引入数据库文件--> 15 <context:property-placeholder location="classpath:jdbc.properties" /> 16 <!--由spring容器来管理Druid数据源--> 17 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 18 <property name="username" value="${jdbc.username}"></property> 19 <property name="password" value="${jdbc.password}"></property> 20 <property name="url" value="${jdbc.url}"></property> 21 <!--注意此处不是driver,而是driverClassName--> 22 <property name="driverClassName" value="${jdbc.driver}"></property> 23 </bean> 24 25 <!--spring整合mybatis--> 26 <bean class="org.mybatis.spring.SqlSessionFactoryBean"> 27 <!--引入数据源--> 28 <property name="dataSource" ref="dataSource"></property> 29 <!--引入mybatis-config.xml--> 30 <property name="configLocation" value="classpath:mybatis-config.xml"></property> 31 <!--引入映射文件BookMapper.xml--> 32 <property name="mapperLocations" value="classpath:fun/jiayou/mapper/*.xml"></property> 33 <!--实体类全限定名(注册包的地址)--> 34 <property name="typeAliasesPackage" value="fun.jiayou.pojo"></property> 35 </bean> 36 <!--创建代理对象--> 37 <mybatis:scan base-package="fun.jiayou.mapper"></mybatis:scan> 38 39 <!--事务管理--> 40 <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 41 <property name="dataSource" ref="dataSource"></property> 42 </bean> 43 <!--注册事务注解驱动--> 44 <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> 45 46 </beans>
7.整合springmvc
(1)创建springmvc-config.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 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"> 7 8 <context:component-scan base-package="fun.jiayou"> 9 <!--指定扫描controller--> 10 <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 11 </context:component-scan> 12 <!--配置视图解析器--> 13 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 14 <property name="prefix" value="/WEB-INF/pages/"></property> 15 <property name="suffix" value=".jsp"></property> 16 </bean> 17 <!--配置默认处理器和注解处理器:分别用于处理控制器方法请求和静态资源请求--> 18 <mvc:default-servlet-handler></mvc:default-servlet-handler> 19 <mvc:annotation-driven></mvc:annotation-driven> 20 21 </beans>
8.web.xml配置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 6 version="2.5"> 7 8 <!--配置filter:解决编码问题--> 9 <filter> 10 <filter-name>characterEncodingFilter</filter-name> 11 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 12 <init-param> 13 <param-name>encoding</param-name> 14 <param-value>UTF-8</param-value> 15 </init-param> 16 </filter> 17 <filter-mapping> 18 <filter-name>characterEncodingFilter</filter-name> 19 <url-pattern>/*</url-pattern> 20 </filter-mapping> 21 22 <!--配置spring容器,tomcat启动时,创建spring容器--> 23 <context-param> 24 <param-name>contextConfigLocation</param-name> 25 <param-value>classpath:spring-config.xml</param-value> 26 </context-param> 27 <listener> 28 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 29 </listener> 30 31 <!--配置DispatcherServlet--> 32 <servlet> 33 <servlet-name>dispatcherServlet</servlet-name> 34 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 35 <init-param> 36 <param-name>contextConfigLocation</param-name> 37 <param-value>classpath:springmvc-config.xml</param-value> 38 </init-param> 39 </servlet> 40 <servlet-mapping> 41 <servlet-name>dispatcherServlet</servlet-name> 42 <url-pattern>/</url-pattern> 43 </servlet-mapping> 44 45 </web-app>
9.创建Controller和service层
(1)controller
1 package fun.jiayou.controller; 2 3 import com.github.pagehelper.PageHelper; 4 import com.github.pagehelper.PageInfo; 5 import fun.jiayou.pojo.Book; 6 import fun.jiayou.service.impl.BookServiceImpl; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.RequestParam; 11 12 import java.util.List; 13 import java.util.Map; 14 15 /** 16 * @author BaiYun 17 * @create 2020-09-04-14:20 18 */ 19 @Controller 20 public class BookController { 21 22 @Autowired 23 BookServiceImpl bookServiceImpl; 24 25 @RequestMapping(value = "queryAllBook") 26 public String queryAllBook( 27 @RequestParam(value = "pageNum",required = false, defaultValue = "1") Integer pageNum, 28 @RequestParam(value = "pageSize",required = false, defaultValue = "2") Integer pageSize, 29 Map<String,Object> maps 30 ) { 31 PageHelper.startPage(pageNum, pageSize); 32 List<Book> books = bookServiceImpl.queryAllBook(); 33 PageInfo<Book> pageInfo = new PageInfo<>(books,3); 34 maps.put("pageInfo", pageInfo); 35 return "bookList"; 36 } 37 38 @RequestMapping(value = "delBookById") 39 public String delBookById(Integer id) { 40 bookServiceImpl.delBook(id); 41 return "redirect:/queryAllBook"; 42 } 43 44 @RequestMapping(value = "forwards") 45 public String forwards() { 46 return "bookEdit"; 47 } 48 49 @RequestMapping(value = "addBook") 50 public String addBook(Book book) { 51 bookServiceImpl.addBook(book); 52 return "redirect:/queryAllBook"; 53 } 54 @RequestMapping(value = "queryBookById") 55 public String queryBookById(Map<String,Object> maps,Integer id) { 56 Book book = bookServiceImpl.queryBookById(id); 57 maps.put("book", book); 58 return "bookEdit"; 59 } 60 61 @RequestMapping(value = "editBook") 62 public String editBook(Book book) { 63 bookServiceImpl.editBook(book); 64 return "redirect:/queryAllBook"; 65 } 66 }
(2)service
1 package fun.jiayou.service.impl; 2 3 import fun.jiayou.mapper.BookMapper; 4 import fun.jiayou.pojo.Book; 5 import fun.jiayou.service.BookService; 6 import org.springframework.beans.factory.annotation.Autowired; 7 import org.springframework.stereotype.Service; 8 9 import java.util.List; 10 11 /** 12 * @author BaiYun 13 * @create 2020-09-04-14:23 14 */ 15 @Service 16 public class BookServiceImpl implements BookService { 17 @Autowired 18 BookMapper bookMapper; 19 20 @Override 21 public List<Book> queryAllBook() { 22 List<Book> books = bookMapper.selectByExample(null); 23 return books; 24 } 25 26 @Override 27 public Book queryBookById(Integer id) { 28 Book book = bookMapper.selectByPrimaryKey(id); 29 return book; 30 } 31 32 @Override 33 public void addBook(Book book) { 34 bookMapper.insertSelective(book); 35 } 36 37 @Override 38 public void delBook(Integer id) { 39 bookMapper.deleteByPrimaryKey(id); 40 } 41 42 @Override 43 public void editBook(Book book) { 44 bookMapper.updateByPrimaryKeySelective(book); 45 } 46 }
10.创建JSP页面
(1)bookList.jsp
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 3 <html> 4 <head> 5 <title>图书信息列表</title> 6 </head> 7 <body> 8 <center> 9 <h2>图书信息列表</h2> 10 <div style="width: 800px;text-align: right"> 11 <a href="${pageContext.request.contextPath}/forwards">添加图书</a> 12 </div> 13 <div> 14 <table style="border-collapse: collapse;text-align: center;" width="800px" border="1"> 15 <tr bgcolor="#FF8888"> 16 <td>书名</td> 17 <td>作者</td> 18 <td>价格</td> 19 <td>销量</td> 20 <td>库存</td> 21 <td>操作</td> 22 </tr> 23 24 <c:forEach items="${requestScope.pageInfo.list}" var="book"> 25 <tr> 26 <td>${book.name}</td> 27 <td>${book.author}</td> 28 <td>${book.price}</td> 29 <td>${book.sales}</td> 30 <td>${book.stock}</td> 31 <td> 32 <a href="${pageContext.request.contextPath}/delBookById?id=${book.id}">删除</a> | 33 <a href="${pageContext.request.contextPath}/queryBookById?id=${book.id}">修改</a> 34 </td> 35 </tr> 36 </c:forEach> 37 </table> 38 <div> 39 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=1">首页</a> 40 <c:if test="${pageInfo.isFirstPage}"> 41 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=1">上一页</a> 42 </c:if> 43 <c:if test="${not pageInfo.isFirstPage}"> 44 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=${pageInfo.pageNum-1}">上一页</a> 45 </c:if> 46 47 <c:forEach items="${pageInfo.navigatepageNums}" var="i" > 48 <c:if test="${pageInfo.pageNum==i}"> 49 <a style="color: red;" href="${pageContext.request.contextPath}/queryAllBook?pageNum=${i}">${i}</a> 50 </c:if> 51 <c:if test="${pageInfo.pageNum != i}"> 52 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum${i}">${i}</a> 53 </c:if> 54 </c:forEach> 55 56 <c:if test="${pageInfo.isLastPage}"> 57 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=${pageInfo.pages}">下一页</a> 58 </c:if> 59 <c:if test="${not pageInfo.isLastPage}"> 60 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=${pageInfo.pageNum+1}">下一页</a> 61 </c:if> 62 <a href="${pageContext.request.contextPath}/queryAllBook?pageNum=${pageInfo.pages}">尾页</a> 63 </div> 64 </div> 65 </center> 66 </body> 67 </html>
(2)bookEdit.jsp
1 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 2 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 3 <html > 4 <head> 5 <title>图书编辑</title> 6 </head> 7 <body> 8 <center> 9 <form action="${pageContext.request.contextPath}/${empty book.id?'addBook':'editBook'}" method="post"> 10 <input type="hidden" name="id" value="${book.id}"> 11 书名:<input type="text" name="name" value="${requestScope.book.name}"><br> 12 作者:<input type="text" name="author" value="${requestScope.book.author}"><br> 13 价格:<input type="text" name="price" value="${requestScope.book.price}"><br> 14 销量:<input type="text" name="sales" value="${requestScope.book.sales}"><br> 15 库存:<input type="text" name="stock" value="${requestScope.book.stock}"><br> 16 <input type="submit" value="提交"> 17 </form> 18 </center> 19 </body> 20 </html>
11.最终效果
(1)tomcat启动情况
(2)CRUD效果
(3)代码打包
链接:https://pan.baidu.com/s/1JjUUnlmdg6o4DdrSIVgvKQ
提取码:mjxw
ps:如有不足之处,请指出。我们共同进步。