ssm整合

SSM整合

环境要求:

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

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

2. 基本环节搭建

新建一个maven项目,ssmbuild,添加web支持,导入相关pom依赖。

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

在pom中注意资源过滤问题

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

构建基本结构和配置框架

  • com.kuang.pojo

  • com.kuang.dao

  • com.kuang.service

  • com.kuang.controller

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

mybatis层编写

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的核心配置文件,这里不放啥东西,起标志我们使用mybatis的作用



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

configuration>

4、编写数据库对应的实体类 com.kuang.pojo.Books

使用lombok插件!

package com.kuang.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

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

5、编写Dao层的 Mapper接口!

package com.kuang.dao;

import com.kuang.pojo.Books;
import java.util.List;
public interface BookMapper {
   //增加一个Book
   int addBook(Books book);
   //根据id删除一个Book
   int deleteBookById(int id);
   //更新Book
   int updateBook(Books books);
   //根据id查询,返回一个Book
   Books queryBookById(int id);
   //查询全部Book,返回list集合
   List<Books> queryAllBook();
}

6、编写接口对应的 Mapper.xml 文件,相当于接口mapper的实现类,但由于不是java类,所以不能直接注入为java的bean。




<mapper namespace="com.kuang.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>
mapper>

编写Service层的接口和实现类

  1. 接口
package com.kuang.service;
import com.kuang.pojo.Books;
import java.util.List;

//BookService:底下需要去实现,调用dao层
public interface BookService {
   //增加一个Book
   int addBook(Books book);
   //根据id删除一个Book
   int deleteBookById(int id);
   //更新Book
   int updateBook(Books books);
   //根据id查询,返回一个Book
   Books queryBookById(int id);
   //查询全部Book,返回list集合
   List<Books> queryAllBook();
}
  1. 实现类
package com.kuang.service;

import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
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(Books book) {
       return bookMapper.addBook(book);
  }   
   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();
  }
}

编写spring层,spring整合mybatis,即(dao,service),spring层自己注册。

1、配置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 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>
   
   
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
       
       <property name="basePackage" value="com.kuang.dao"/>
   bean>
beans>

3、Spring整合service层,spring-service.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
   http://www.springframework.org/schema/context/spring-context.xsd">
   
   <context:component-scan base-package="com.kuang.service" />
   
   <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
       <property name="bookMapper" ref="bookMapper"/>
   bean>
   
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       
       <property name="dataSource" ref="dataSource" />
   bean>
beans>
  1. springmvc层,在web.xml中注册DispatcherServlet,DispatcherServlet关联的是整个上下文配置文件。

<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>
  1. spring-mvc.xml,配置controller扫描,注册这里面的bean。还有视图解析器。
 
<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.kuang.controller" />

beans>

然后为spring-mvc.xml,spring-service.xml,spring-dao.xml配置一个总的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="spring-dao.xml"/>
   <import resource="spring-service.xml"/>
   <import resource="spring-mvc.xml"/>
   
beans>

Controller 和 视图层编写

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";
   }
   @RequestMapping("/toAddBook")
	   public String toAddPaper() {
       return "addBook";
   }

   @RequestMapping("/addBook")
   public String addPaper(Books books) {
       System.out.println(books);
       bookService.addBook(books);
       return "redirect:/book/allBook";
   }
   @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";
   }
}

2、编写首页 index.jsp

<%@ 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、书籍列表页面 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>
   <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>

   <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="${requestScope.get('list')}">
                   <tr>
                       <td>${book.getBookID()}td>
                       <td>${book.getBookName()}td>
                       <td>${book.getBookCounts()}td>
                       <td>${book.getDetail()}td>
                       <td>
                           <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改a> |
                           <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除a>
                       td>
                   tr>
               c:forEach>
               tbody>
           table>
       div>
   div>
div>

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