SSM整合及CRUD实现

文章目录

  • 1. 基本环境搭建
  • 2. Mybaitis层
  • 3. Spring层
  • 4. SpringMVC
  • 5. CRUD业务测试

1. 基本环境搭建

数据库

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,'从进门到进牢');

创建项目导入依赖

<dependencies>
   
   <dependency>
       <groupId>junitgroupId>
       <artifactId>junitartifactId>
       <version>4.12version>
   dependency>
   
   <dependency>
       <groupId>mysqlgroupId>
       <artifactId>mysql-connector-javaartifactId>
       <version>5.1.47version>
   dependency>
   
   <dependency>
       <groupId>com.mchangegroupId>
       <artifactId>c3p0artifactId>
       <version>0.9.5.2version>
   dependency>

   
   <dependency>
       <groupId>javax.servletgroupId>
       <artifactId>servlet-apiartifactId>
       <version>2.5version>
   dependency>
   <dependency>
       <groupId>javax.servlet.jspgroupId>
       <artifactId>jsp-apiartifactId>
       <version>2.2version>
   dependency>
   <dependency>
       <groupId>javax.servletgroupId>
       <artifactId>jstlartifactId>
       <version>1.2version>
   dependency>

   
   <dependency>
       <groupId>org.mybatisgroupId>
       <artifactId>mybatisartifactId>
       <version>3.5.2version>
   dependency>
   <dependency>
       <groupId>org.mybatisgroupId>
       <artifactId>mybatis-springartifactId>
       <version>2.0.2version>
   dependency>

   
   <dependency>
       <groupId>org.springframeworkgroupId>
       <artifactId>spring-webmvcartifactId>
       <version>5.1.9.RELEASEversion>
   dependency>
   <dependency>
       <groupId>org.springframeworkgroupId>
       <artifactId>spring-jdbcartifactId>
       <version>5.1.9.RELEASEversion>
   dependency>
dependencies>

maven资源过滤

<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>

mybatis-config.xml



<configuration>

configuration>

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>

2. Mybaitis层

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=123456

2.IDEA关联数据库
3.编写MyBatis的核心配置文件



<configuration>
    <typeAliases>
        <package name="com.zh.pojo"/>
    typeAliases>
    <mappers>
        <mapper resource="com/zh/dao/BookMapper.xml"/>
    mappers>
configuration>

4.编写数据库对应的实体类
要导入lombok依赖

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
  private int bookId;
  private String bookName;
  private int bookCounts;
  private String detail;

}

5.编写Dao层的 Mapper接口

public interface BookMapper {
    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById(@Param("bookId") int id);
    //更新Book
    int updateBook(Books book);
    //根据id查询返回一个Book
    Books queryBookById(@Param("bookId") int id);
    //查询全部Book
    List<Books> queryAllBook();
    //根据书名查询
    Books queryBookByName(String name);
}


6.编写接口对应的 Mapper.xml 文件



<mapper namespace="com.zh.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="queryBookById" resultType="Books">
        select * from ssmbuild.books where bookID = #{bookId}
    select>
    <select id="queryAllBook" resultType="Books">
      SELECT * from ssmbuild.books
   select>
    <select id="queryBookByName" resultType="Books" >
        select * from ssmbuild.books where bookName like concat('%',#{name},'%')
    select>
mapper>

7.编写Service层的接口和实现类

public interface BookService {
    //增加一个Book
    int addBook(Books book);
    //根据id删除一个Book
    int deleteBookById( int id);
    //更新Book
    int updateBook(Books book);
    //根据id查询返回一个Book
    Books queryBookById( int id);
    //查询全部Book
    List<Books> queryAllBook();
    //根据书名查询
    Books queryBookByName(String name);
}


public class BookServiceImpl implements BookService{
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    public int addBook(Books book) {
        return bookMapper.addBook(book);
    }

    public int deleteBookById(int id) {
        return bookMapper.deleteBookById(id);
    }

    public int updateBook(Books book) {
        return bookMapper.updateBook(book);
    }

    public Books queryBookById(int id) {
        return bookMapper.queryBookById(id);
    }

    public List<Books> queryAllBook() {
        return bookMapper.queryAllBook();
    }

    public Books queryBookByName(String name) {
        return bookMapper.queryBookByName(name);
    }
}


3. Spring层

配置Spring整合MyBatis,数据源使用c3p0连接池
编写Spring整合Mybatis的相关的配置文件;spring-dao.xml


<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">

    
    
    <context:property-placeholder location="classpath:database.properties"/>
    
    
    <bean name="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>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.zh.dao"/>
    bean>
beans>

Spring整合service层


<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">

    
    <context:component-scan base-package="com.zh.service" />

    
    <bean id="BookServiceImpl" class="com.zh.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource" />
    bean>

beans>

注意在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">
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
beans>

4. SpringMVC

web.xml


<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>DispatcherServletservlet-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>DispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>
            org.springframework.web.filter.CharacterEncodingFilter
        filter-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>

web-app>

spring-mvc.xml


<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">

    
    
    <mvc:annotation-driven />
    
    <mvc:default-servlet-handler/>

    
    <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>

    
    <context:component-scan base-package="com.zh.controller" />

beans>

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">
    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
beans>

5. CRUD业务测试

1.BookController 类编写 , 方法一:查询全部书籍

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;
    //查询全部书籍,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list", list);
        return "allBook";
    }

}

2.首页

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<html>
<head>
   <title>首页title>
   <style type="text/css">
       a {
           text-decoration: none;
           color: black;
           font-size: 18px;
      }
       h3 {
           width: 180px;
           height: 38px;
           margin: 100px auto;
           text-align: center;
           line-height: 38px;
           background: deepskyblue;
           border-radius: 4px;
      }
   style>
head>
<body>

<h3>
   <a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页a>
h3>
body>
html>

3.书籍列表页面

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>书籍列表title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>

<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表 —— 显示所有书籍small>
                h1>
            div>
        div>
    div>

    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增a>
        div>
        <div class="col-md-4 column">div>
        <div class="col-md-4 column">
            <form action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                <input type="text" name="queryBookName" class="form-control" placeholder="输入查询书籍的名称">
                <input type="submit" value="查询" class="btn btn-primary">
            form>
        div>
    div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>书籍编号th>
                    <th>书籍名字th>
                    <th>书籍数量th>
                    <th>书籍详情th>
                    <th>操作th>
                tr>
                thead>

                <tbody>
                <c:forEach var="book" items="${list}">
                    <tr>
                        <th>${book.bookID}th>
                        <th>${book.bookName}th>
                        <th>${book.bookCounts}th>
                        <th>${book.detail}th>
                        <th><a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改a> |
                            <a href="${pageContext.request.contextPath}/book/del?id=${book.getBookID()}">删除a>
                        th>
                    tr>

                c:forEach>
                tbody>
            table>
        div>
    div>
div>

4.添加书籍
controller

   //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }
    //添加书籍
    @RequestMapping("/addBook")
    public String addPaper(Books book){
        System.out.println(book);
        bookService.addBook(book);
        //重定向到书籍列表页面
        return "redirect:/book/allBook";
    }

addBook.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>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增书籍small>
                h1>
            div>
        div>
    div>
    <form action="${pageContext.request.contextPath}/book/addBook" method="post">
        书籍名称:<input type="text" name="bookName"><br><br><br>
        书籍数量:<input type="text" name="bookCounts"><br><br><br>
        书籍详情:<input type="text" name="detail"><br><br><br>
        <input type="submit" value="添加">
    form>

div>

5.修改书籍
controller

   //跳转到更新书籍页面
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id){
        Books books = bookService.queryBookById(id);
        System.out.println(books);
        model.addAttribute("book",books);
        return "updateBook";
    }
    //更新书籍
    @RequestMapping("/updateBook")
    public String updateBook(Model model,Books book){
        System.out.println(book);
        bookService.updateBook(book);
        Books books = bookService.queryBookById(book.getBookID());
        model.addAttribute("books",books);
        return "redirect:/book/allBook";
    }

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>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
head>
<body>
<div class="container">

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>修改信息small>
                h1>
            div>
        div>
    div>

    <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
        <input type="hidden" name="bookID" value="${book.getBookID()}"/>
        书籍名称:<input type="text" name="bookName" value="${book.getBookName()}"/>
        书籍数量:<input type="text" name="bookCounts" value="${book.getBookCounts()}"/>
        书籍详情:<input type="text" name="detail" value="${book.getDetail() }"/>
        <input type="submit" value="提交"/>
    form>

div>

6.删除书籍
controller

  //删除书籍
    @RequestMapping("/del")
    public String deleteBook(int id){
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }

7.模糊查询书籍
controller

 //查询书籍
    @RequestMapping("/queryBook")
    public String queryBook(String queryBookName,Model model){
        Books book = bookService.queryBookByName(queryBookName);
        List<Books> list = new ArrayList<Books>();
        list.add(book);
        model.addAttribute("list", list);
        return "allBook";
    }

测试
主页面
SSM整合及CRUD实现_第1张图片
新增
SSM整合及CRUD实现_第2张图片
SSM整合及CRUD实现_第3张图片
更改
SSM整合及CRUD实现_第4张图片
SSM整合及CRUD实现_第5张图片
删除
SSM整合及CRUD实现_第6张图片
查询
SSM整合及CRUD实现_第7张图片

你可能感兴趣的:(框架,数据库,列表,spring,java,mybatis)