1. 程式人生 > 其它 >Redis與資料庫之間的處理

Redis與資料庫之間的處理

·前言

  剛通過視訊學完mybatis、spring、springMVC,做了一個SSM框架的整合。此框架是結合了視訊中老師的思路,按照自己的理解進行整合的。這是原出處:http://dwz.date/ac27。框架設計了一個圖書表,並可以通過前端web頁面對圖書表進行增刪改查等操作。由於沒有前端基礎,頁面比較簡陋。同時,程式碼不夠規範,大小寫格式沒有按照規範來。希望以後可以注意到並改正。

·整合步驟:

(1)通過maven建立一個不使用模板的專案,設定GAV(groupId、artifactId、version),並把專案設定成web專案

(2)建立資料庫 :

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

(3)匯入依賴包,在pom.xml中配置:

<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.20</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.4</version> </dependency> </dependencies>

(4)設定靜態資源過濾,在pom.xml中配置:

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

(5)建立專案基本結構(建立每一層的包):

  entity、dao、service、controller

(6)建立基礎框架配置:

    1.在resources資料夾中建立mybatis-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>
</configuration>

    2.在resources資料夾中建立applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"      
   xsi:schemaLocation
="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd"> </beans>

(7)在resources資料夾中建立資料庫配置檔案 database.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuilduseSSL=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123

(8)IDEA關聯資料庫

(9)編寫實體類:在entity下建立Books類:

package com.zyf.entity;

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;

}

(10)編寫dao層的BooksMapper介面:

    package com.zyf.dao;

    import com.zyf.entity.Books;
    import org.apache.ibatis.annotations.Param;
    import java.util.List;

    public interface BooksMapper {
        int addBooks(Books books);
        int deleteBooks(@Param("bookID") int id);
        int updateBooks(Books books);
        Books queryBooksById(@Param("bookID")int id);
        List<Books> queryAllBooks();
    }

(11)編寫BooksMapper.xml實現介面BooksMapper:

<?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.zyf.dao.BooksMapper">
        <insert id="addBooks" parameterType="Books">
        insert into mybatis.books  values (#{bookID},#{bookName},#{bookCounts},#{detail});
        </insert>
        <delete id="deleteBooks" parameterType="int">
        delete from  mybatis.books where bookID=#{bookID};
        </delete>
        <update id="updateBooks" parameterType="Books">
        update mybatis.books set bookName = #{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID};
        </update>
        <select id="queryBooksById" resultType="Books">
        select * from mybatis.books where bookID=#{bookID};
        </select>
        <select id="queryAllBooks" resultType="Books">
        select * from mybatis.books;
        </select>
    </mapper>

  在編寫該程式碼的時候,需要在resources/mybatis-config.xml中,定義別名以及註冊該mapper.xml:

    <typeAliases>
          <package name="com.zyf.entity"/>
       </typeAliases>

       <mappers>
         <mapper resource="com/zyf/dao/BooksMapper.xml"/>
       </mappers>

(12)編寫service層BooksService介面:

    package com.zyf.service;

    import com.zyf.entity.Books;
    import java.util.List;

    public interface BooksService {
        int addBooks(Books books);
        int deleteBooks(int id);
        int updateBooks(Books books);
        Books queryBooksById(int id);
        List<Books> queryAllBooks();
    }

(13)編寫service層BooksService的實現類BooksServiceImpl:

        package com.zyf.service;

        import com.zyf.dao.BooksMapper;
        import com.zyf.entity.Books;
        import java.util.List;

        public class BooksServiceImpl implements BooksService{
            //呼叫dao層的操作,設定一個set介面,方便Spring管理
            private BooksMapper booksMapper;
            public void setBooksMapper(BooksMapper booksMapper){
            this.booksMapper=booksMapper;
            }

            public int addBooks(Books books) {
            return booksMapper.addBooks(books);
            }

            public int deleteBooks(int id) {
            return booksMapper.deleteBooks(id);
            }

            public int updateBooks(Books books) {
            return booksMapper.updateBooks(books);
            }

            public Books queryBooksById(int id) {
            return booksMapper.queryBooksById(id);
            }

            public List<Books> queryAllBooks() {
            return booksMapper.queryAllBooks();
            }
        }

(14)編寫resources/applicationContext.xml檔案:

     <?xml version="1.0" encoding="UTF-8"?>
        <beans xmlns="http://www.springframework.org/schema/beans"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               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
               https://www.springframework.org/schema/context/spring-context.xsd
               http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">

            <!--1.關聯資料庫配置檔案-->
            <context:property-placeholder location="classpath:database.properties"/>
            <!--2.注入資料庫連線池-->
            <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物件,設定連線池和mybatis配置檔案的位置-->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            </bean>
            <!--4.MapperScannerConfigurer 自動掃描 將Mapper介面生成代理注入到Spring-->
            <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.zyf.dao"/>
            </bean>
            <!--5.將BookServiceImpl注入到容器中-->
            <!--當使用註解的方式注入時候,需要加入掃描程式碼<context:component-scan base-package="com.zyf.service" />-->
            <bean id="BookServiceImpl" class="com.zyf.service.BooksServiceImpl">
            <property name="booksMapper" ref="booksMapper"/>
            </bean>
            <!--6.配置事務管理器-->
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
            </bean>
            <!--截止到6mybatis已經整合完畢,從7開始配置SpringMVC,即控制層以及請求等等的相關內容-->
            <!--7.開啟springMVC註解驅動,並設定JSON為utf-8-->
            <mvc:annotation-driven>
            <mvc:message-converters>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                    <value>text/html;charset=utf-8</value>
                    </list>
                </property>
                </bean>
            </mvc:message-converters>
            </mvc:annotation-driven>
            <!--8..靜態資源預設servlet配置-->
            <mvc:default-servlet-handler/>
            <!--9.由於使用了註解所以需要掃描-->
            <context:component-scan base-package="com.zyf.controller"/>
            <!--10.配置檢視解析器-->
            <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>

(15)編寫web.xml配置:

    <!--設定前端控制器-->
        <servlet>
        <servlet-name>dispatcherServlet</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>
        <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
        </servlet-mapping>
        <!--設定過濾器,此為一個編碼型別的設定-->
        <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
        </filter>
        <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!--設定一個session的過期時間-->
        <session-config>
        <session-timeout>15</session-timeout>
        </session-config>

(16)編寫控制層BooksController:

    package com.zyf.controller;

        import com.zyf.entity.Books;
        import com.zyf.service.BooksService;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.factory.annotation.Qualifier;
        import org.springframework.stereotype.Controller;
        import org.springframework.ui.Model;
        import org.springframework.web.bind.annotation.PathVariable;
        import org.springframework.web.bind.annotation.RequestMapping;
        import java.util.List;

        @Controller
        @RequestMapping("/Books")
        public class BooksController {
            @Autowired
            @Qualifier("BookServiceImpl")
            private BooksService booksService;

            @RequestMapping("/All")
            public String queryAllBooks(Model model) {
            List<Books> list = booksService.queryAllBooks();
            model.addAttribute("books", list);
            return "AllBooks";
            }
            @RequestMapping("/toAddBooks")
            public String toAddBooks() {
            //使用此方法,可以跳轉到WEB-INF下面的jsp頁面
            return "AddBooks";
            }
            @RequestMapping("/AddBooks")
            public String AddBooks(Books books) {
            System.out.println(books);
            booksService.addBooks(books);
            return "redirect:/Books/All";
            }
            @RequestMapping("/DeleteBooks/{bookID}")
            public String DeleteBooks(@PathVariable("bookID") int bookID) {
            booksService.deleteBooks(bookID);
            return "redirect:/Books/All";
            }
            @RequestMapping("/toUpdate")
            public String toUpdate(int id, Model model) {
            Books books = booksService.queryBooksById(id);
            model.addAttribute("books", books);
            return "UpdateBooks";
            }
            @RequestMapping("/UpdateBooks")
            public String UpdateBooks(Books books) {
            booksService.updateBooks(books);
            return "redirect:/Books/All";
            }
        }

(17)編寫前端:1.主頁面(index.jsp):

            <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>$Title$</title>
            </head>
            <body>
            <a href="${pageContext.request.contextPath}/Books/All">檢視所有書籍</a>
            </body>
            </html>

    2.展示所有書籍頁面(AllBooks.jsp):

            <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
            <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>展示所有書籍</title>
            </head>
            <body>
            <p><a href="${pageContext.request.contextPath}/Books/toAddBooks">新增書籍</a></p>
            <table>
                <thead>
                <tr>
                <th>書籍編號</th>
                <th>書籍名字</th>
                <th>書籍數量</th>
                <th>書籍詳情</th>
                <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="book" items="${books}">
                <tr>
                    <th>${book.bookID}</th>
                    <th>${book.bookName}</th>
                    <th>${book.bookCounts}</th>
                    <th>${book.detail}</th>
                    <th><a href="${pageContext.request.contextPath}/Books/toUpdate?id=${book.bookID}">修改</a>|<a
                        href="${pageContext.request.contextPath}/Books/DeleteBooks/${book.bookID}">刪除</a></th>
                </tr>
                </c:forEach>
                </tbody>
            </table>
            </body>
            </html>

    3.新增書籍頁面(AddBooks.jsp):

        <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>新增書籍</title>
            </head>
            <body>
            <form action="${pageContext.request.contextPath}/Books/AddBooks" method="post">
                書籍名字:<input type="text" name="bookName"/><br>
                書籍數量:<input type="text" name="bookCounts"/><br>
                書籍詳情:<input type="text" name="detail"/><br>
                <input type="submit" name="新增"/>
            </form>
            </body>
            </html>

    4.修改書籍頁面(UpdateBooks.jsp):

            <%@ page contentType="text/html;charset=UTF-8" language="java" %>
            <html>
            <head>
                <title>Title</title>
            </head>
            <body>
            <form action="${pageContext.request.contextPath}/Books/UpdateBooks" method="post">
                <input type="hidden" name="bookID" value="${books.bookID}">
                書籍名字:<input name="bookName" type="text" value="${books.bookName}"><br>
                書籍數量:<input name="bookCounts" type="text" value="${books.bookCounts}"><br>
                書籍詳情:<input name="detail" type="text" value="${books.detail}"><br>
                <input type="submit" name="修改">
            </form>
            </body>
            </html>

(18)開啟project structure,把包匯入

·初步建立專案後執行遇到的問題:

(1)applicationContext.xml的頭沒有寫全
(2)最後添加了Jackson的包沒有在project structure中新增
(3)空指標報錯異常檢查:web.xml配置的前段控制器繫結的配置檔案是否包含了所有配置、控制層呼叫的service的介面是new出來的還是spring的,new出來的是錯誤的。