精华内容
下载资源
问答
  • 使用SSM框架实现增删改查等功能,包括数据库文件。hhh
  • 如有web开发项目请联系QQ:1490232044,包含mysql和SqlServer的demo
  • 一套基于SpringBoot+SSM框架增删改查模板。适合新手学习SSM
  • ssm单表增删改查

    2018-05-04 15:06:43
    ssm 单表增删改查 ssm 单表增删改查 ssm 单表增删改查
  • spring+springMVC+Mybatis实现学生管理系统增删改查,数据库中有两张表:student学生和class班级表。使用Myabtis逆向生成以及分页插件,以及批量操作,前端使用bootstrap框架搭建。
  • SSM 框架整合 增删改查在页面展示

    千次阅读 2020-03-01 22:18:31
    以前要配置数据源,现在整合后交给spring去做 -- > < ! -- 配置别名 -- > < typeAliases > < package name = "com.heng.pojo" / > < / typeAliases > < ! -- 扫描包下的所有xml文件 -- > < ...

    1.导入依赖(创建数据库)

        <!--依赖: junit 数据库驱动 连接池 servlet jsp mybatis mybatis-spring 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.47</version>
            </dependency>
            <!-- 数据库连接池 -->
            <dependency>
                <groupId>com.mchange</groupId>
                <artifactId>c3p0</artifactId>
                <version>0.9.5.2</version>
            </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>
    
            <!--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.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.10</version>
            </dependency>
        </dependencies>
    <!--资源过滤-->
        <build>
            <resources>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
                <resource>
                    <directory>src/main/resources</directory>
                    <includes>
                        <include>**/*.properties</include>
                        <include>**/*.xml</include>
                    </includes>
                    <filtering>false</filtering>
                </resource>
            </resources>
        </build>
    

    数据库建表语句

    数据库环境
    创建一个存放书籍数据的数据库表
    
    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.建包

    com.heng.controller 控制视图跳转
    com.heng.dao 接口,操作数据库
    com.heng.pojo 实体类
    com.heng.service 业务层
    Spring
    spring-dao.xml
    spring-mvc.xml
    spring-service.xml
    mybatis-config.xml
    applicationContext.xml
    database.properties

    3编写Mbtis-config.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>
    
    <!--以前要配置数据源,现在整合后交给spring去做-->
        <!--配置别名-->
        <typeAliases>
            <package name="com.heng.pojo"/>
        </typeAliases>
        <!--扫描包下的所有xml文件-->
        <mappers>
            <package name="com.heng.pojo"/>
        </mappers>
    
    </configuration>
    

    3. 创建实体类(User)

    实体类字段需要和数据库一一对应

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

    4.在dao层编写接口BookMapper

    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();
    }
    

    5.编写接口配置文件 BookMapper.xml 需要绑定到mybatis-config.xml文件中

    一个mapper对应一个接口 所有多个接口需要写多个mapper
    一个mapper需要绑定一个接口文件的位置

    <?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 namespace="com.heng.dao.BookMapper">
    
        <!--增加一个Book-->
        <insert id="addBook" parameterType="Books">
            insert into ssmbuild.books(bookName,bookCounts,detail)
            values (#{bookName}, #{bookCounts}, #{detail})
        </insert>
    
        <!--根据id删除一个Book-->
        <delete id="deleteBookById" parameterType="int">
            delete from ssmbuild.books where bookID=#{bookID}
        </delete>
    
        <!--更新Book-->
        <update id="updateBook" parameterType="Books">
            update ssmbuild.books
            set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
            where bookID = #{bookID}
        </update>
    
        <!--根据id查询,返回一个Book-->
        <select id="queryBookById" resultType="Books">
            select * from ssmbuild.books
            where bookID = #{bookID}
        </select>
    
        <!--查询全部Book-->
        <select id="queryAllBook" resultType="Books">
            SELECT * from ssmbuild.books
        </select>
    </mapper>
    

    6.编写业务层BookService 业务层和dao层对应

    没有本质的区别都是操作数据库

    //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();
    }
    

    7.业务层编写完成后,需要写实现类BookServiceImpl

    public class BookServiceImpl implements BookService {
    
         //调用dao层的操作,组合dao
        // 设置一个set接口,方便Spring管理
        //可以在业务层进行一些操作直接用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();
        }
    }
    

    7.整合dao 编写spring-dao.xml(数据库配置文件编写database.properties) IOC实现

    连接数据库的参数 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
    

    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">
    
        <!-- 配置整合mybatis -->
        <!-- 1.关联数据库文件,之前连接数据库文件需要使用Mybatis-config.xml去配置  整合以后直接配置到spring中 context:property-placeholder location="classpath:database.properties"固定写法   -->
        <context:property-placeholder location="classpath:database.properties"/>
    
        <!-- 2.数据库连接池 -->
        <!--数据库连接池
    dbcp  半自动化操作  不能自动连接
    c3p0  自动化操作(自动的加载配置文件 并且设置到对象里面)
    druid   企业常用数据库
    hikart  spring默认数据库
        -->
        <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}"/>
    
    
            <!-- 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  Sql会话工厂对象 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <!-- 注入数据库连接池 -->
            <property name="dataSource" ref="dataSource"/>
            <!-- 绑定MyBaties现在spring和MyBatis就联合起来了  绑定的文件mybatis-config.xml -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
        
        
    <!--编写以下下面的配置就不需要再去dao层编写实现类BookMapperImpl同过去继承SqlSessionDaoSupport实现BookMapper,
    重写方法注册到SqlSessionFactory-->
        
        <!-- 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="com.heng.dao"/>
        </bean>
    
    </beans>
    

    8.整合业务层service 编写spring-service.xml 可以实现AOP

    <?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">
    
        <!--1. 扫描service下所有的有注解的包 -->
        <context:component-scan base-package="com.heng.service" />
    
        <!--2.将我们的所有的业务类,注册到Spring,可以通过配置,或者注解实现-->
        <!--BookServiceImpl注入到IOC容器中-->
        <bean id="BookServiceImpl" class="com.heng.service.BookServiceImpl">
            <property name="bookMapper" ref="bookMapper"/>
        </bean>
    
        <!--3. 配置事务管理器 -->
        <!--声明是为配置-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <!-- 注入数据库源-->
            <property name="dataSource" ref="dataSource" />
        </bean>
    
        <!--4.可以添加事务支持aop-->
    
    </beans>
    

    9.编写Spring-mvc.xml 首先需要添加web支持 编写web.xml文件

    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">
    
        <!--使用spring-mvc后这里面的代码不需要在动了-->
    
        <!--所有的请求被核心DispatcherServlet分发器接管-->
        <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:applicationContext.xml</param-value>
            </init-param>
            <!--和temacat一起启动-->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Springmvc</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>
    
        <!--为了安全起见配置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
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!--前端配置-->
        
        <!-- 配置web.xml SpringMVC配置文件 -->
        <!-- 1.开启SpringMVC注解驱动 -->
        <mvc:annotation-driven />
        <!-- 2.静态资源默认servlet配置-->
        <mvc:default-servlet-handler/>
        <!-- 3.扫描web相关的bean -->
        <context:component-scan base-package="com.heng.controller" />
    
        <!-- 4.配置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>
    </beans>
    

    到此为止三个框架整合完成建议保存以后的基础框架搭建

    10.开始业务实现编写BookController

    查询所有的书籍,并且返回到一个书籍的展示页面 编写页面allBook.jsp
    index.xml 首页

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
    <!DOCTYPE HTML>
    <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>
    

    页面渲染的结果
    在这里插入图片描述
    点击进入列表会发起一个请求http://localhost:8080//book/allBook执行 返回一个allBook页面

    @Controller
    @RequestMapping("/book")
    public class BookController {
        //controller 调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";
        }
        }
    

    编写allBook 页面

    <%@ 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">
        <!-- 引入 Bootstrap 美化页面-->
        <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="${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>
    

    跳转结果
    在这里插入图片描述

    11.添加一个书籍首先编写标签跳转页面的方法

     //跳转到书籍页面
        @RequestMapping("/toAddBook")
        public String toAddBook(Books books) {
            System.out.println(books);
            return "addBook";
        }
    

    12.addBook.jsp 编写书籍页面提交后的需要重定向的页面allBook

    <%@ 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">
        <!-- 引入 Bootstrap -->
        <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>
    

    添加数据页面
    在这里插入图片描述
    提交后的页面
    在这里插入图片描述

    13.修改书籍,点击修改跳转到修改页面

    点击修改执行页面跳转

      //跳转到修改页面
        @RequestMapping("/toUpdete")
        public String toUpdetePaper(Model model, int id) {
            Books books = bookService.queryBookById(id);
            System.out.println(books);
            model.addAttribute("qbook",books );
            return "updateBook";
        }
    

    编写修改的页面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">
        <!-- 引入 Bootstrap -->
        <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="${qbook.getBookID()}"/>
            书籍名称:<input type="text" name="bookName" value="${qbook.getBookName()}"/>
            书籍数量:<input type="text" name="bookCounts" value="${qbook.getBookCounts()}"/>
            书籍详情:<input type="text" name="detail" value="${qbook.getDetail() }"/>
            <input type="submit" value="修改"/>
        </form>
    
    </div>
    
    

    修改参数 点击修改提交
    在这里插入图片描述
    修改提交走这串代码实现页面跳转

       //修改书籍
        @RequestMapping("/updateBook")
        public String updateBook(Model model, Books book) {
            System.out.println(book);
            bookService.updateBook(book);
            return "redirect:/book/allBook";
        }
    

    跳转到书籍展示页
    在这里插入图片描述

    14.删除书籍

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

    删除前
    在这里插入图片描述
    删除后直接调用service业务成去调用到层实现sql语句
    在这里插入图片描述

    15.新增加一个功能 根据名字查询

    1.首先编写一个查询框jsp页面

    <div class="col-md-4 column"></div>
            <div class="col-md-4 column">
               <form class="form-inline" action="${pageContext.request.contextPath}/book/queryBook" method="post" style="float: right">
                   <span style="color: red;font-weight: bold">${error}</span>
                  <input type="text" name="queryBookName" class="form-control" placeholder="请输入查询的书籍名称">
                   <input type="submit" value="查询" class="btn btn-primary">
               </form>
    

    在这里插入图片描述
    2.编写dao底层接口和SQL语句.

    
        //根据书名字查询书
        Books queryBookBuName(@Param("bookName") String bookName);
    
       <!--String 类型可以不写-->
        <select id="queryBookBuName" resultType="Books">
           select * from ssmbuild.books
           where bookName =#{bookName}
        </select>
    

    3.然后编写service的接口和实现类

    //根据书名字查询书
        Books queryBookBuName(@Param("bookName") String bookName);
    
      public Books queryBookBuName(String bookName) {
            return bookMapper.queryBookBuName(bookName);
        }
    

    4.controller 控制页面跳转

      //查询书籍
        @RequestMapping("queryBook")
        public String queryBook(String queryBookName,Model model){
            Books books = bookService.queryBookBuName(queryBookName);
            ArrayList<Books> list = new ArrayList<Books>();
            list.add(books);
            if (books==null){
                list= (ArrayList<Books>) bookService.queryAllBook();
                model.addAttribute("error","未找到" );
            }
    
            model.addAttribute("list", list);
            return "allBook";
    
        }
    

    包结构目录
    在这里插入图片描述

    展开全文
  • 本代码为ssm框架(spring+springmvc+mybatis),实现数据库的增删改查功能!
  • 文章目录核心步骤具体实现创建maven Webapp工程...整合Spring 整合Mybatis 具体实现 创建maven Webapp工程 mvn org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate -DarchetypeArtifactId="maven-archet

    核心步骤

    1. 创建maven webapp工程
    2. 在工程的pom.xml中添加依赖
    3. 搭建SpringMvc的基本环境
    4. 整合Spring
    5. 整合Mybatis
    6. SSM开启事务管理

    具体实现

    创建maven Webapp工程

    cmd界面使用以下命令创建工程

    mvn org.apache.maven.plugins:maven-archetype-plugin:3.1.2:generate -DarchetypeArtifactId="maven-archetype-webapp" -DarchetypeGroupId="org.apache.maven.archetypes" -DarchetypeVersion="1.4"
    

    pom.xml中添加依赖

    <dependencies>
        <!--junit-->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
        </dependency>
        <!--Spring-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-core</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aop</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.aspectj</groupId>
          <artifactId>aspectjweaver</artifactId>
          <version>1.9.6</version>
        </dependency>
        <!--SpringMvc-->
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>5.3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>5.3.1</version>
        </dependency>
        <!--json-->
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-core</artifactId>
          <version>2.12.0-rc2</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.12.0-rc2</version>
        </dependency>
        <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-annotations</artifactId>
          <version>2.12.0-rc2</version>
        </dependency>
         <!--servlet3 4版本不行-->
        <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
        </dependency>
        <!--druid-->
        <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.1.10</version>
        </dependency>
        <!--mybatis-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.5.6</version>
        </dependency>
        <!--mybatis-spring-->
        <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>2.0.6</version>
        </dependency>
        <!--mysql-->
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>8.0.19</version>
        </dependency>
      </dependencies>
    

    搭建SpringMvc的环境

    • 编写SpringMvc的配置类
    @ComponentScan("com.dean.controller")
    @EnableWebMvc
    public class WebConfig implements WebMvcConfigurer {
    
        //视图解析器
        @Override
        public void configureViewResolvers(ViewResolverRegistry registry) {
            InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
            viewResolver.setPrefix("/WEB-INF/views/");
            viewResolver.setSuffix(".jsp");
            registry.viewResolver(viewResolver);
        }
    
        //配置静态资源:允许访问静态资源
        @Override
        public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    
        //配置主页面:设定/默认返回页面
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("index");  //index会自动与视图解析器的前后缀结合
        }
    }
    
    
    • 编写前端控制器UserController
    @RestController
    @RequestMapping("/user")
    public class UserController {
    }
    
    • 编写启动类
    public class WebServerInit extends AbstractAnnotationConfigDispatcherServletInitializer {
        //Spring
        @Override
        protected Class<?>[] getRootConfigClasses() {
            return new Class[0];
        }
    
        //SpringMvc
        @Override
        protected Class<?>[] getServletConfigClasses() {
            return new Class[]{WebConfig.class};
        }
    
        //Mapping
        @Override
        protected String[] getServletMappings() {
            return new String[]{"/"};
        }
    }
    
    
    • 编写前端页面
      在这里插入图片描述
      测试后显示主页面如下:
      在这里插入图片描述

    整合Spring

    整合Spring,主要就是编写三层架构

    • 配置类AppConfig,并在WebServerInit中配置
    @ComponentScan("com.dean.service")
    public class AppConfig {
    }
    

    WebServerInit中的getRootConfigClasses

    在这里插入图片描述

    • 完成Service接口并编写test方法
    @Service
    public class UserServiceIm implements UserService {
        @Override
        public void test() {
            System.out.println("User Service test");
        }
    }
    
    • UserController中注入UserService并调用test方法
      在这里插入图片描述
    • 测试结果
      在这里插入图片描述

    整合MyBatis

    通过Spring托管数据源

    • 编写资源文件data.properties,提供连接数据库的参数
    jdbc.url=jdbc:mysql://192.168.100.2:3306/ssm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.user=root
    jdbc.pwd=****  #填写自己的密码
    
    • AppConfig中指定资源文件位置 并将数据源注入到容器
    @Configuration
    @ComponentScan("com.dean.service")
    @PropertySource({"classpath:data.properties"})    //指定资源文件路径
    public class AppConfig {
        @Autowired
        private Environment env;
        @Bean("dataSource")     //注入数据源到Spring容器
        public DataSource dataSource()
        {
            String driver=env.getProperty("jdbc.driver");
            String url=env.getProperty("jdbc.url");
            String username=env.getProperty("jdbc.user");
            String pwd=env.getProperty("jdbc.pwd");
    
            DruidDataSource dataSource=new DruidDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(pwd);
    
            return dataSource;
        }
    }
    

    通过Spring托管Session工厂

    • AppConfig中注入SqlSessionFactoryBean
    @Bean
        public SqlSessionFactoryBean getSessionFactory(@Qualifier("dataSource") DataSource dataSource)
        {
            SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(dataSource);
    
            return sqlSessionFactoryBean;
        }
    
    • 在controller中进行测试

    在这里插入图片描述
    测试结果
    在这里插入图片描述

    创建Mapper接口和对象关系映射文件

    • 创建pojo类
      数据库中表格式如下:
      在这里插入图片描述
      pojo类
    //@Data是lombok中的注释
    //lombok与IDEA 2020版本不兼容,需要自己去下载插件,百度搜索解决方式即可
    @Data 
    public class User {
        private String id;
        private String name;
        private Integer age;
        private Date birth;
    }
    
    • 编写Mapper查询接口和对象映射文件UserMapper.xml
      Mapper查询接口
    public interface UserMapper {
       List<User> findAll();
    
    }
    

    对象映射文件

    <?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 namespace="com.dean.mapper.UserMapper">
        <resultMap id="baseMap" type="com.dean.model.User">
            <id property="id" column="ID"></id>
            <result property="name" column="NAME"></result>
            <result property="age" column="AGE"></result>
            <result property="birth" column="BIRTH"></result>
        </resultMap>
    
        <select id="findAll" resultMap="baseMap">
            select * from user;
        </select>
    
    
    </mapper>
    

    配置Mybatis,(mapper接口位置、对象映射文件所在位置)

    • AppConfig中配置Mapper查询接口所在的位置
      在这里插入图片描述
    • AppConfig中的Session工厂中配置对象关系映射文件所在的位置
      在这里插入图片描述

    MyBatis整合完成测试

    在Controller层进行测试
    在这里插入图片描述
    启动tomcat后显示结果
    在这里插入图片描述
    与数据库数据一致

    ssm管理事务

    • 准备工作,编写一个新增用户的接口
      前端视图
    <form action="/user/addUser" method="post">
        <p>
            <label for="name">Name:</label>
            <input type="text" id="name" name="name">
        </p>
        <p>
            <label for="age">Age:</label>
            <input type="text" id="age" name="age">
        </p>
        <p>
            <label for="birth">Birth:</label>
            <input type="date" id="birth" name="birth">
        </p>
        <p>
            <input type="submit" value="添加用户">
        </p>
    </form>
    

    前端控制器

    @PostMapping("/addUser")
        public ModelAndView addUser(User user) throws Exception  
        {
            user.setId(UUID.randomUUID().toString());
            userService.addUser(user);
            return new ModelAndView("success");
        }
    

    Service层代码:抛出异常后应回滚

    @Override
        public void addUser(User user) throws Exception {
            userMapper.addUser(user);        int count=userMapper.selectCount(user.getName());
            //判断用户是否唯一,如果不唯一,则进行回滚
            if(count>1)
            {
                throw new RuntimeException("用户名已被注册");
            }
        }
    
    • 在AppConfig中配置事务管理器,并通过注释开启事务管理
    @Bean
        public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("dataSource") DataSource dataSource)
        {
            DataSourceTransactionManager transactionManager=new DataSourceTransactionManager(dataSource);
            return transactionManager;
        }
    

    在AppConfig的头部添加注释开启事务管理
    在这里插入图片描述

    • 在Service层目标方法处添加注释使用事务
      在这里插入图片描述
    • 附加:进行统一异常处理
      编写统一异常类
    @ControllerAdvice
    public class BasicControllerAdvice {
        //对自定义异常的处理
        @ExceptionHandler(RuntimeException.class)
        public ModelAndView customError(Exception e, Model model)
        {
            //将异常信息放入model
            model.addAttribute("message",e.getMessage());
            return new ModelAndView("error");
        }
    }
    
    

    将advice层加入容器
    在SpringMVC的配置类WebConfig中扫描advice的路径
    在这里插入图片描述

    展开全文
  • Java整合SSM框架实现用户信息的和批量删除的应用实例
  • SSM框架整合实现增删改查(简单的实现)

    万次阅读 多人点赞 2018-09-24 19:17:41
    SSM框架整合实现增删改查 文件结构 POM文件 &lt;packaging&gt;war&lt;/packaging&gt; &lt;!-- 处理乱码 --&gt; &lt;properties&gt; &lt;!-- 设置项目字符集 --&gt; ...

    SSM框架整合实现增删改查


    文件结构
    在这里插入图片描述
    POM文件

    <packaging>war</packaging>
      <!-- 处理乱码 -->
    	<properties>
    		<!-- 设置项目字符集 -->
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<!-- spring版本号 -->
    		<spring.version>4.3.2.RELEASE</spring.version>
    	</properties>
      <dependencies>
      <!--Dao层Mybatis  jar包  -->
      		<!-- mybatis -->
      		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis</artifactId>
    			<version>3.4.5</version>
    		</dependency>
      		<!-- mysql -->
      		<dependency>
    			<groupId>mysql</groupId>
    			<artifactId>mysql-connector-java</artifactId>
    			<version>8.0.11</version>
    		</dependency>
      		<!-- druid -->
      		<dependency>
    			<groupId>com.alibaba</groupId>
    			<artifactId>druid</artifactId>
    			<version>1.1.8</version>
    		</dependency>
    	<!-- Service层 Spring -->
    		<!-- Spring-context -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-context</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-core -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-core</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-bean -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-beans</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-expression -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-expression</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-tx -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-tx</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-jbdc -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-jdbc</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-mybatis -->
    		<dependency>
    			<groupId>org.mybatis</groupId>
    			<artifactId>mybatis-spring</artifactId>
    			<version>1.3.2</version>
    		</dependency>
    	<!-- Servlet层SpringMVC -->
    		<!-- Spring-web -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-web</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- Spring-mvc -->
    		<dependency>
    			<groupId>org.springframework</groupId>
    			<artifactId>spring-webmvc</artifactId>
    			<version>4.3.2.RELEASE</version>
    		</dependency>
    		<!-- servlet -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>javax.servlet-api</artifactId>
    			<version>4.0.1</version>
    			<scope>provided</scope>
    		</dependency>
    		<!-- jsp -->
    		<dependency>
    			<groupId>javax.servlet.jsp</groupId>
    			<artifactId>javax.servlet.jsp-api</artifactId>
    			<version>2.3.3</version>
    			<scope>provided</scope>
    		</dependency>
    		<!-- jsp.jstl -->
    		<dependency>
    			<groupId>javax.servlet.jsp.jstl</groupId>
    			<artifactId>jstl</artifactId>
    			<version>1.2</version>
    		</dependency>
    		<!-- servlet.jstl -->
    		<dependency>
    			<groupId>javax.servlet</groupId>
    			<artifactId>jstl</artifactId>
    			<version>1.2</version>
    		</dependency>
    		<!-- standard -->
    		<dependency>
    			<groupId>taglibs</groupId>
    			<artifactId>standard</artifactId>
    			<version>1.1.2</version>
    		</dependency>
    	<!-- aspect注解 -->
    		<!--使用AspectJ方式注解需要相应的包 --> 
    		<dependency>
    			<groupId>org.aspectj</groupId>
    			<artifactId>aspectjrt</artifactId>
    			<version>1.6.11</version>
    		</dependency>
    		<!--使用AspectJ方式注解需要相应的包 -->
    		<dependency>
    			<groupId>org.aspectj</groupId>
    			<artifactId>aspectjweaver</artifactId>
    			<version>1.6.11</version>
    		</dependency>
      </dependencies>
      <!-- Tomcat插件 -->
      		<build>
    		<!-- 配置tomcat插件,web端 -->
    		<plugins>
    			<plugin>
    				<groupId>org.apache.tomcat.maven</groupId>
    				<artifactId>tomcat7-maven-plugin</artifactId>
    				<configuration>
    					<path>/</path>
    					<port>8080</port>
    				</configuration>
    			</plugin>
    		</plugins>
    	</build>
    

    Mybatis的XML文件
    applicationContext-mybatis.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:p="http://www.springframework.org/schema/p"
    	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-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
        
        <!-- 加载数据库配置文件 -->
        <context:property-placeholder location="classpath:druid.properties"/>
        <!-- 配置数据库连接池 -->
        <bean id="dataSource"
    		class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    		destroy-method="close">
    		<!-- 配置数据库连接基本信息 -->
    		<property name="driverClassName" value="${driver}" />
    		<property name="url" value="${url}" />
    		<property name="username" value="${name}" />
    		<property name="password" value="${password}" />
    		<!-- ******配置数据库连接池相关信息******* -->
    		<!-- 配置初始化大小、最小、最大 -->
    		<property name="initialSize" value="5" />
    		<property name="minIdle" value="2" />
    		<property name="maxActive" value="10" />
    		<!-- 配置获取连接等待超时的时间 -->
    		<property name="maxWait" value="10000" />
    		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    		<property name="timeBetweenEvictionRunsMillis" value="60000" />
    		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    		<property name="minEvictableIdleTimeMillis" value="300000" />
    		<property name="testWhileIdle" value="true" />
    		<!-- 这里建议配置为TRUE,防止取到的连接不可用 -->
    		<property name="testOnBorrow" value="true" />
    		<property name="testOnReturn" value="false" />
    		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
    		<property name="poolPreparedStatements" value="true" />
    		<property name="maxPoolPreparedStatementPerConnectionSize"
    			value="20" />
    		<!-- 这里配置提交方式,默认就是TRUE,可以不用配置 -->
    		<property name="defaultAutoCommit" value="true" />
    		<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
    		<property name="validationQuery" value="select 1" />
    	</bean>
    	<!-- sqlsessionFactory -->
    	<bean id="sqlSessionFactoryBean"
    		class="org.mybatis.spring.SqlSessionFactoryBean">
    		<!-- 注入数据源 -->
    		<property name="dataSource" ref="dataSource"></property>
    		<!-- 加载mybatis配置文件 -->
    		<property name="configLocation" value="classpath:mybatisConfig.xml"></property>
    		<!-- 加载映射文件 -->
    		<property name="mapperLocations" value="classpath:cn/edu360/mybatis/entity/*.xml"></property>
    	</bean>
    	<!-- 配置事物管理器 -->
    	<bean id="transactionManager"
    		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<!-- 注入数据源 -->
    		<property name="dataSource" ref="dataSource"></property>
    	</bean>
    	<!-- 通过aop管理事务(事务应该做用在service层) -->
    	<aop:config proxy-target-class="true">
    		<aop:advisor pointcut="execution (* cn.edu360.service.impl.*.*(..))"
    			advice-ref="departmentAdvice" />
    	</aop:config>
    	<!-- 创建一个事物 -->
    	<tx:advice id="departmentAdvice"
    		transaction-manager="transactionManager">
    		<!-- 设置事物的级别和属性 -->
    		<tx:attributes>
    			<tx:method name="insert*" isolation="READ_COMMITTED"
    				propagation="REQUIRED" read-only="false" timeout="-1"
    				rollback-for="Exception" />
    			<tx:method name="delete*" isolation="READ_COMMITTED"
    				propagation="REQUIRED" read-only="false" timeout="-1"
    				rollback-for="Exception" />
    			<tx:method name="update*" isolation="READ_COMMITTED"
    				propagation="REQUIRED" read-only="false" timeout="-1"
    				rollback-for="Exception" />
    			<tx:method name="select*" propagation="SUPPORTS"
    				read-only="false" rollback-for="Exception" />
    			<tx:method name="*" isolation="READ_COMMITTED"
    				propagation="REQUIRED" timeout="-1" rollback-for="Exception"
    				read-only="false" />
    		</tx:attributes>
    	</tx:advice>
    	<!-- 扫描Dao层连接Mybatis的mapper接口 -->
    	<bean id="mapperScannerConfigurer"
    		class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<property name="basePackage" value="cn.edu360.mybatis.mapper"></property>
    		<property name="sqlSessionFactoryBeanName"
    			      value="sqlSessionFactoryBean"></property>
    	</bean>
    </beans>
    

    Mybatis配置文件
    mybatisConfig.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>
    
    </configuration>
    

    Spring配置文件
    applicationContext-spring.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:p="http://www.springframework.org/schema/p"
    	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-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
        <!-- 启用classpath扫描 -->
        <context:component-scan base-package="cn.edu360"></context:component-scan>
    
    </beans>
    

    SpringMVC配置文件
    springmvc.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:p="http://www.springframework.org/schema/p"
    	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-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
        
        <!-- classpath扫描controller -->
        <context:component-scan base-package="cn.edu360.spring.controller"></context:component-scan>
        <!-- springMVC 视图解析器 -->
        <bean
    		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix" value="/" />
    		<property name="suffix" value=".jsp" />
    	</bean>
    
    </beans>
    

    web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
      <display-name>Spring-SpringMVC-Mybatis-ssm</display-name>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
      <!-- 在servlet上下文中配置ioc容器文件 -->
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:applicationContext-*.xml</param-value>
    	</context-param>
    	<!-- 通过监听器加载ioc容器 -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	<!-- 配置过滤器 -->
    	<!-- POST中文乱码过滤器 -->
    	<filter>
    		<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    	<!-- 配置前端控制器 -->
    	<servlet>
    		<servlet-name>DispatcherServlet</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<!-- 默认加载springmvc配置文件【servlet-name】-servlet.xml 位置在WEB-INF下 -->
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>classpath:springmvc.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>
    </web-app>
    

    实体类

    package cn.edu360.mybatis.entity;
    
    public class Department {
    	private int department_id;
    	private String dname;
    	private String daddress;
    
    	public Department(int department_id, String dname, String daddress) {
    		super();
    		this.department_id = department_id;
    		this.dname = dname;
    		this.daddress = daddress;
    	}
    
    	public Department() {
    		super();
    	}
    
    	public int getDepartment_id() {
    		return department_id;
    	}
    
    	public void setDepartment_id(int department_id) {
    		this.department_id = department_id;
    	}
    
    	public String getDname() {
    		return dname;
    	}
    
    	public void setDname(String dname) {
    		this.dname = dname;
    	}
    
    	public String getDaddress() {
    		return daddress;
    	}
    
    	public void setDaddress(String daddress) {
    		this.daddress = daddress;
    	}
    
    	@Override
    	public String toString() {
    		return "Department [department_id=" + department_id + ", dname=" + dname + ", daddress=" + daddress + "]";
    	}
    
    }
    

    Mapping映射文件

    <?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 namespace="cn.edu360.mybatis.mapper.DepartmentMapper">
    	<!-- 添加 -->
    	<insert id="insertByCount" parameterType="cn.edu360.mybatis.entity.Department">
    		insert into department values(null,#{dname},#{daddress})
    	</insert>
    	<!-- 修改 -->
    	<update id="updateByCount" parameterType="cn.edu360.mybatis.entity.Department">
    		update department set dname=#{dname},daddress=#{daddress} where department_id=#{department_id}
    	</update>
    	<!-- 删除 -->
    	<delete id="deleteByCount" parameterType="cn.edu360.mybatis.entity.Department">
    		delete from department where department_id=#{department_id}
    	</delete>
    	<!-- 查询全部 -->
    	<select id="selectByAll" resultType="cn.edu360.mybatis.entity.Department">
    		select * from department
    	</select>
    	<!-- 模糊查询 -->
    	<select id="selectByLike" resultType="cn.edu360.mybatis.entity.Department" parameterType="java.lang.String">
    		select * from department where dname like concat('%',#{keyWord},'%')
    	</select>
    </mapper>
    

    Mapper接口

    package cn.edu360.mybatis.mapper;
    
    import java.util.List;
    
    import cn.edu360.mybatis.entity.Department;
    
    public interface DepartmentMapper {
    	//对数据库进行添加
    	int insertByCount(Department dept);
    	//对数据库进行修改
    	int updateByCount(Department dept);
    	//对数据库进行删除
    	int deleteByCount(Department dept);
    	//对数据路进行全部查找
    	List<Department> selectByAll();
    	//对数据库进行模糊查询
    	List<Department> selectByLike(String keyWord);
    }
    
    

    Service接口

    package cn.edu360.service.inter;
    
    import java.util.List;
    
    import cn.edu360.mybatis.entity.Department;
    
    public interface DepartmentServiceInter {
    	String insertByCount(Department dept);
    	String updateByCount(Department dept);
    	String deleteByCount(Department dept);
    	List<Department> selectByAll();
    	List<Department> selectByLike(String keyWord);
    }
    
    

    Service实现类

    package cn.edu360.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import cn.edu360.mybatis.entity.Department;
    import cn.edu360.mybatis.mapper.DepartmentMapper;
    import cn.edu360.service.inter.DepartmentServiceInter;
    @Service("departmentServiceImpl")
    public class DepartmentServiceImpl implements DepartmentServiceInter {
    	@Autowired
    	private DepartmentMapper departmentMapper;
    	@Override
    	public String insertByCount(Department dept) {
    		System.out.println("service+++++++++++++++++++++++++++++++++++++++++++++");
    		int i = departmentMapper.insertByCount(dept);
    		String message="";
    		if(i>0) {
    			message="添加成功";
    		}else {
    			message="添加失败";
    		}
    		return message;
    	}
    
    	@Override
    	public String updateByCount(Department dept) {
    		int i = departmentMapper.updateByCount(dept);
    		String message="";
    		if(i>0) {
    			message="修改成功";
    		}else {
    			message="修改失败";
    		}
    		return message;
    	}
    
    	@Override
    	public String deleteByCount(Department dept) {
    		int i = departmentMapper.deleteByCount(dept);
    		String message="";
    		if(i>0) {
    			message="删除成功";
    		}else {
    			message="删除失败";
    		}
    		return message;
    	}
    
    	@Override
    	public List<Department> selectByAll() {
    		return departmentMapper.selectByAll();
    	}
    
    	@Override
    	public List<Department> selectByLike(String keyWord) {
    		return departmentMapper.selectByLike(keyWord);
    	}
    
    	public DepartmentMapper getDepartmentMapper() {
    		return departmentMapper;
    	}
    
    	public void setDepartmentMapper(DepartmentMapper departmentMapper) {
    		this.departmentMapper = departmentMapper;
    	}
    	
    }
    

    Controller控制层

    package cn.edu360.spring.mybatis.test;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.ibatis.annotations.ResultMap;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;
    
    import cn.edu360.mybatis.entity.Department;
    import cn.edu360.service.impl.DepartmentServiceImpl;
    import cn.edu360.service.inter.DepartmentServiceInter;
    @Controller
    public class SpringMybatisTest { 
    	@Autowired
    	private  DepartmentServiceInter service;
    	@RequestMapping("/insert")
    	public String insertByCount(HttpServletRequest req,Department dept) {
    		
    		dept.setDname(dept.getDname());
    		dept.setDaddress(dept.getDaddress());
    		System.out.println(dept.toString());
    		String insert = service.insertByCount(dept);
    		req.setAttribute("insert", insert);
    		
    		return "/insert";
    	}
    	@RequestMapping("/select")
    	public String selectByAll(HttpServletRequest req){
    		List<Department> list = service.selectByAll();
    		req.setAttribute("list", list);
    		return "/select";
    		
    	}
    	@RequestMapping("/update")
    	public String updateByCount(HttpServletRequest req,Department dept) {
    		dept.setDname(dept.getDname());
    		dept.setDaddress(dept.getDaddress());
    		dept.setDepartment_id(dept.getDepartment_id());
    		String update = service.updateByCount(dept);
    		req.setAttribute("update", update);
    		return "/update";
    	}
    	@RequestMapping("/delete")
    	public String deleteByCount(HttpServletRequest req,Department dept) {
    		dept.setDepartment_id(dept.getDepartment_id());
    		String delete = service.deleteByCount(dept);
    		req.setAttribute("delete", delete);
    		return "/delete";
    	}
    }
    

    JSP页面
    查询展示页面
    在这里插入图片描述

    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>部门列表</title>
    </head>
    <body>
    	<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
    		<thead>
    			<tr style="text-align: left;">
    			<form action="insert.jsp" method="post" enctype="application/x-www-form-urlencoded">
    				<td colspan="3">
    					<input type="submit" value="添加"/>
    				</td>
    			</form>
    			<form action="delete.jsp" method="post" enctype="application/x-www-form-urlencoded">
    				<td colspan="3">
    					<input  type="submit" value="删除"/>
    				</td>
    			</form>
    			</tr>
    			<tr style="text-align: center;">
    				<td><input type="checkbox" id="checkAll"/></td>
    				<th>部门ID</th>
    				<th>部门名称</th>
    				<th>部门地址</th>
    				<th>操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<c:forEach items="${ list }" var="p">
    			<tr style="text-align: center;">
    				<td><input type="checkbox" class="checkSimple" value="${ p.department_id }"/></td>
    				<th>${ p.department_id }</th>
    				<th>${ p.dname }</th>
    				<th>${ p.daddress }</th>
    				<td><a href="/update.jsp">修改</a></td>
    			</tr>
    			</c:forEach>
    		</tbody>
    	</table>
    </body>
    </html>
    

    添加界面
    在这里插入图片描述

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加</title>
    </head>
    <body>
    <form action="insert" method="post" enctype="application/x-www-form-urlencoded">
    	<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
    		<thead>
    			<tr style="text-align: center;">
    				<td><input type="checkbox" id="checkAll"/></td>
    				<th>部门名称</th>
    				<th>部门地址</th>
    				<th>商品操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<tr>
    				<td><input type="checkbox" class="checkSimple"/></td>
    				<td><input type="text" name="dname" id="dname"></td>
    				<td><input type="text" name="daddress" id="daddress"></td>
    				<td><input type="submit" id="add" value="添加"/></td>
    			</tr>
    		</tbody>
    	</table>
    	<p style="color:red">${insert}</p> 
    	</form>
    </body>
    </html>
    

    更改界面
    在这里插入图片描述

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>修改</title>
    </head>
    <body>
    	<form action="/update" method="post" enctype="application/x-www-form-urlencoded">
    	<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
    		<thead>
    			<tr style="text-align: center;">
    				<td><input type="checkbox" id="checkAll"/></td>
    				<th>部门ID</th>
    				<th>部门名称</th>
    				<th>部门地址</th>
    				<th>商品操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<tr>
    				<td><input type="checkbox" class="checkSimple"/></td>
    				<td><input type="text" name="department_id" id="department_id"></td>
    				<td><input type="text" name="dname" id="dname"></td>
    				<td><input type="text" name="daddress" id="daddress"></td>
    				<td><input type="submit" id="update" value="修改"/></td>
    			</tr>
    		</tbody>
    	</table>
    	<p style="color: red">${update}</p>
    	<a href="/select">返回</a>
    	</form>
    </body>
    </html>
    

    删除界面
    在这里插入图片描述

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>删除</title>
    </head>
    <body>
    	<form action="/delete" method="post" enctype="application/x-www-form-urlencoded">
    	<table border="solid 1px red;" cellspacing="0px" cellpadding="5px" width="600px" >
    		<thead>
    			<tr style="text-align: center;">
    				<td><input type="checkbox" id="checkAll"/></td>
    				<th>部门ID</th>
    				<th>商品操作</th>
    			</tr>
    		</thead>
    		<tbody>
    			<tr>
    				<td><input type="checkbox" class="checkSimple"/></td>
    				<td><input type="text" name="department_id" id="department_id"></td>
    				<td><input type="submit" id="delete" value="删除"/></td>
    			</tr>
    		</tbody>
    	</table>
    	<p style="color: red">${delete}</p>
    	<a href="/select">返回</a>
    	</form>
    </body>
    </html>
    
    展开全文
  • maven、spring、spring mvc、mybatis 整合实现ssm通用增删改查基础开发框架.maven、spring、spring mvc、mybatis 整合实现ssm通用增删改查基础开发框架.maven、spring、spring mvc、mybatis 整合实现ssm通用增删改查...
  • 基于SSM框架增删改查

    千次阅读 多人点赞 2019-12-16 19:33:13
    SSM整合开发是目前企业流行使用的框架整合方案,这篇博客给出了实现逻辑以及源码

    写在前面: 我是「扬帆向海」,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。

    这博客是对自己学习的一点点总结及记录,如果您对 Java算法 感兴趣,可以关注我的动态,我们一起学习。

    用知识改变命运,让我们的家人过上更好的生活

    源码地址: https://github.com/zhangxycg/ssm_crud

    如要查看源码,请点击我

    视频地址: https://www.bilibili.com/video/av21045215

    尚硅谷Java视频教程

    一、使用的技术

        基础框架: ssm(SpringMVC + Spring + MyBatis)
        前端框架: Bootstrap
        数据库: MySQL
        项目的依赖管理: Maven
        分页: pagehelper
        逆向工程: MyBatis Generator
    

    二、环境的搭建

    1. 创建一个maven工程

    2. 在pom文件中引入项目依赖的jar包
      • spring
      • springmvc
      • mybatis
      • 数据库连接池(c3p0)
      • mysql驱动包
      • 其他(jstl,servlet-api,junit)

    3. 引入bootstrap前端框架

    4. 编写ssm整合的关键配置文件
      web.xml,spring,springmvc,mybatis,使用mybatis的逆向工程生成对应的 pojo 以及 mapper

    5. 测试mapper

    项目使用的表结构

    部门表

    CREATE TABLE `tbl_dept` (
      `dept_id` int(11) NOT NULL AUTO_INCREMENT,
      `dept_name` varchar(255) NOT NULL,
      PRIMARY KEY (`dept_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    

    员工表

    CREATE TABLE `tbl_emp` (
      `emp_id` int(11) NOT NULL AUTO_INCREMENT,
      `emp_name` varchar(255) NOT NULL,
      `gender` char(1) DEFAULT NULL,
      `email` varchar(255) DEFAULT NULL,
      `d_id` int(11) DEFAULT NULL,
      PRIMARY KEY (`emp_id`),
      KEY `fk_emp_dept` (`d_id`),
      CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tbl_dept` (`dept_id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2020 DEFAULT CHARSET=utf8;
    

    三、页面效果图

    在这里插入图片描述

    四、项目结构图

    在这里插入图片描述

    五、功能及其实现逻辑

    1. 查询功能

    1. 在浏览器访问 index.jsp 页面
    2. index.jsp 页面发出查询员工列表的请求
    3. 后台 EmployeeController 接收前台发过来的请求,查出员工数据
    4. 来到 list.jsp 页面进行展示查询出的数据
    5. pageHelper 分页插件完成分页查询功能

    2. 新增功能

    在这里插入图片描述

    1. 在 index.jsp 页面点击 “ 新增 ” 按钮
    2. 弹出员工新增的对话框
    3. 然后去数据库查询部门列表,显示在对话框中
    4. 用户输入数据,并进行校验
    5. jquery前端校验,ajax用户名重复校验,重要数据(后端校验使用了JSR303);
    6. 数据填写正确,点击保存按钮

    3. 修改功能

    在这里插入图片描述

    1. 在页面点击 “编辑” 按钮
    2. 弹出用户修改的模态框
    3. 修改数据(用户名无法修改)
    4. 修改完成,点击 “更新 ” 按钮,完成用户修改

    4. 删除功能

    在这里插入图片描述

    1. 单个删除
      点击删除按钮,弹出提示信息,点击确定。将会删除数据
    2. 批量删除
      勾选员工姓名前的选择框,可以实现批量删除

    六、 踩坑

    第一次踩坑连接不上数据库 ,报错信息如下

    java.sql.SQLException: The server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    	at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    	at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:835)
    	at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:455)
    	at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
    	at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:199)
    	at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)
    	at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)
    	at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)
    	at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)
    	at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1138)
    	at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1125)
    	at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)
    	at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1870)
    	at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)
    Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: The server time zone value '?й???????' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
    	at sun.reflect.GeneratedConstructorAccessor45.newInstance(Unknown Source)
    	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    	at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
    	at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
    	at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2243)
    	at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2267)
    	at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1319)
    	at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:966)
    	at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:825)
    	... 12 more
    
    
    

    在这里插入图片描述
    报错原因是

    在使用mysql的jdbc驱动最新版(6.0+)版本时,数据库和系统时区差异引起的问题。

    解决办法:

    第一种是 降低驱动的版本

    第二种是:在jdbc连接的url后面加上 ?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&characterEncoding=UTF8

    在这里插入图片描述

    第二次踩坑字新增与修改完成以后,员工数据不按 id 进行升序排列

    解决办法:

    修改 EmployeeMapper.xml 中的查询语句,使员工数据按 员工 id 进行升序排列
    在这里插入图片描述

    <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
            select
            <if test="distinct">
                distinct
            </if>
            <include refid="WithDept_Column_List" />
            FROM tbl_emp e
            left join tbl_dept d on e.`d_id`=d.`dept_id`
            <if test="_parameter != null">
                <include refid="Example_Where_Clause" />
            </if>
            <!-- 员工数据根据id进行升序排列 -->
            order by e.`emp_id`  asc
        </select>
    
    展开全文
  • ssm框架整合(最简单的增删改查

    万次阅读 多人点赞 2019-01-22 09:44:00
    myEclipse+jdk1.8+tomcat7+ssm框架需要jar https://pan.baidu.com/s/1eNn658Hkncm4z28yQtEqxg 提取码:18fd 二、项目结构截图: 三、配置文件详细配置: 1、web.xml配置文件: &lt;!-- SpringMVC前端控制器配置...
  • SSM框架实现完整的增删改查,提供初学者参考
  • 使用SSM框架实现增删改查操作SSM整合mybatisSSM整合SpringSSM整合Spring-MVC SSM整合mybatis 首先这是我们最后整合出来的一个系统的框架,大概的所需要的内容目录如下图所示: pom.xml文件中需要导入的依赖 <...
  • 纯净SSM简单整合,数据库资源根据实体类自己创建。内有ssm增删改查,ajax结合jquery做下拉框,省市联动,多选框等。所有jar包都放在lib里,搭好数据库完美可用。供新手学习。
  • SSM整合(spring+spring-mvc+mybatis)一.简介二.开发工具三.开发步骤1.先创建工程(按步骤来就行)2.补全工程结构3.开始配置文件四.效果图五.结束 一.简介 Spring:是一个开源框架,它由Rod Johnson创建。它是为了...
  • 使用SSM框架实现增删改查

    千次阅读 多人点赞 2018-10-06 00:24:14
    springmvc的理解:... 本项目的jsp页面使用bootstrap前端框架:https://blog.csdn.net/qq_41879385/article/details/82431238 编译器eclipse,数据库MySQL5.5.25,jdk1.8,tomca...
  • ssm框架整合 文章目录ssm框架整合前言一、SSM框架中各层级间的作用及关系?二、使用步骤1.设计数据库,建表2.导入相关依赖导入依赖之后,需要检查WEB-INF/lib目录下面是否有jar包,如果没有需要手动导入,不然访问...
  • ssm框架整合增删改查

    千次阅读 2019-04-24 15:21:42
    <artifactId>ssm_select <name>test <packaging>war <version>1.0.0-BUILD-SNAPSHOT <!-- jdk版本 --> <java-version>1.8 <!-- spring版本 --> <org.springframework-version>4.3.7.RELEASE <!-- ...
  • SSM框架整合+简单的增删改查的实现

    千次阅读 2019-09-22 17:09:23
    SSM框架整合 1.整合注意事项 1.1 查看不同MyBatis版本整合Spring时使用的适配包; 1.2 下载整合适配包 https://github.com/mybatis/spring/releases 1.3 官方整合示例,jpetstore ...2.整合思路、步骤 ...
  • ssm整合框架以及增删改查的分页Demo,简单的客户管理系统。

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,261
精华内容 1,704
关键字:

ssm框架整合的增删改查