MyBatis項目配置案例詳解與Web下的增刪改查實現[附項目源碼]

MyBatis項目案例

項目圖示:css

項目源碼地址:https://github.com/JluTiger/mybatisprohtml

一、項目功能

項目案例:後臺管理系統用戶數據維護平臺java

  • 全部用戶數據查詢mysql

  • 單個用戶數據查詢jquery

  • 用戶數據修改(完善資料)git

  • 鎖定用戶賬號github

  • 刪除用戶賬號(可撤回)web

  • 完全刪除用戶帳號sql

二、數據表建立

  • 數據庫:MySQL 8.0數據庫

  • 數據庫名稱:mydb

  • 數據表:用戶表(users)

# 建立數據庫
CREATE DATABASE mydb;
USE mydb;

CREATE TABLE users(
	id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用戶編號',
	username VARCHAR(50) NOT NULL COMMENT '登陸帳號',
	userpass VARCHAR(50) NOT NULL COMMENT '登陸密碼',
	nickname VARCHAR(50) NOT NULL COMMENT '暱稱',
	age INT COMMENT '用戶年齡',
	gender VARCHAR(5) COMMENT '用戶性別',
	phone VARCHAR(13) COMMENT '聯繫方式',
	email VARCHAR(20) COMMENT '用戶郵箱',
	createTime DATETIME COMMENT '帳號建立時間',
	updateTime DATETIME COMMENT '帳號最後修改時間',
	lastLogin DATETIME COMMENT '帳號最後一次登陸時間',
	userStatus INT COMMENT '用戶賬號狀態 0 正常 1 鎖定 2 刪除',
	remark TEXT COMMENT '備註'
);

SELECT * FROM users;

三、界面準備工做

  • 開發工具:Intellij

  • 使用技術:

    • HTML + CSS + Bootstrap

第一步--->>>>簡單的web項目配置與發佈:

  • pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.mybatis</groupId>
    <artifactId>mybatis-pro</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

</project>
  • 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_3_1.xsd"
         id="WebApp_ID" version="3.1">
    <display-name>mybatispro</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>

</web-app>
  • index.jsp
<%--
  Created by IntelliJ IDEA.
  User: JluTiger
  Date: 2019/5/13
  Time: 16:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>慕課網用戶管理中心</title>
</head>
<body>
    <h1>用戶管理中心</h1>
</body>
</html>

以後配置Tomcat本地服務器發佈便可。

第二步--->>>>界面優化

對index.jsp進行修改,使用Bootstrap和jquery進行美化

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>慕課網用戶管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/jquery-3.3.1/jquery-3.3.1.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="page-header">
            <h1>慕課網後臺管理系統 <small>用戶數據管理中心</small></h1>
        </div>
    </div>

    <div class="row">
        <div class="jumbotron">
            <div class="container">
                <h1>MyBatis基礎入門課程!</h1>
                <p>經過一個項目來完成基礎部分的學習</p>
                <p><a class="btn btn-primary btn-lg" href="#" role="button">查看更多,請上慕課網</a></p>
            </div>
        </div>
    </div>
    <div class="row">
        <table class="table table-hover table-striped">
            <tr>
                <th>用戶編號</th>
                <th>登陸賬號</th>
                <th>用戶暱稱</th>
                <th>郵箱</th>
                <th>聯繫方式</th>
                <th>帳號建立時間</th>
                <th>用戶狀態</th>
                <th>操做</th>
            </tr>

            <tr>
                <th>1</th>
                <th>admin</th>
                <th>小木</th>
                <th>10086@email.com</th>
                <th>12465456</th>
                <th>2017-12-4</th>
                <th>正常</th>
                <th>
                    <a href="">查看</a>
                    <a href="">修改</a>
                    <a href="">刪除</a>
                </th>
            </tr>
        </table>

    </div>
</div>
</body>
</html>

四、基礎操做——MyBatis主配置解析

  • properties配置加載

  • environments環境加載

  • settings環境配置

  • typeAliases別名設置

  • mapper映射加載

首先添加MyBatis依賴:

  • pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo.mybatis</groupId>
    <artifactId>mybatis-pro</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
    </dependencies>
</project>

以後進行MyBatis的相關配置:

  • 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>
    <!--
    properties配置,用於加載外部的properties配置文件
    -->
    <properties resource="db.properties"></properties>

    <!--
    environments 主要用戶數據源的配置
    能夠配置多個數據源,經過default屬性來指定當前項目運行過程當中使用的是哪一個數據源
    -->
    <environments default="development">
        <!--
        environment 用於配置一個具體的獨立的數據源
        id屬性用於給當前數據源定義一個名稱,方便咱們的項目指定
        -->
        <environment id="development">
            <!--
            transactionManager用於配置事務管理,默認狀況下使用的是JDBC事務管理
            -->
            <transactionManager type="JDBC"/>
            <!-- 使用數據庫鏈接池 -->
            <!--
            dataSource具體數據源的鏈接信息:type屬性用於指定是否使用數據庫鏈接池
            -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

        <environment id="product">
            <transactionManager type="JDBC"/>
            <!-- 使用數據庫鏈接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>

        <environment id="test">
            <transactionManager type="JDBC"/>
            <!-- 使用數據庫鏈接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--mappers主要用於配置咱們外部的映射配置文件,在主配置中須要引入加載映射配置文件
        映射配置文件的路徑
    -->
    <mappers>
        <!-- mapper主要配置引入某一個具體的映射文件,resource進行路徑方式的引入-->
        <mapper resource="mapper/usersMapper.xml"></mapper>
    </mappers>
</configuration>
  • db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF8&serverTimezone=PRC&useSSL=false
username=root
password=******

以後建立實體類對象:

  • Users.java
import java.util.Date;

public class Users {
    private Integer id;         //用戶編號
    private String username;    //登陸賬號
    private String userpass;    //登陸密碼
    private String nickname;    //用戶暱稱
    private Integer age;        //用戶年齡
    private String gender;      //用戶性別
    private String phone;       //聯繫方式
    private String email;       //用戶郵箱
    private Date createTime;    //建立時間
    private Date updateTime;    //帳號最後修改時間
    private Date lastLogin;     //帳號最後登陸時間
    private Integer userStatus; //用戶狀態 0 正常 1 鎖定 2 刪除
    private String remark;      //用戶備註信息

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpass() {
        return userpass;
    }

    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Date getLastLogin() {
        return lastLogin;
    }

    public void setLastLogin(Date lastLogin) {
        this.lastLogin = lastLogin;
    }

    public Integer getUserStatus() {
        return userStatus;
    }

    public void setUserStatus(Integer userStatus) {
        this.userStatus = userStatus;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }
}

進行SqlSessionFactory的鏈接:

  • SqlSessionFactoryUtils.java
package com.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    private static String RESOURCE = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /**
     * 建立一個初始化SqlSessionFactory的方法
     * */
    public static void initSqlSessionFactory(){
        try {
            InputStream is = Resources.getResourceAsStream(RESOURCE);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 獲取工廠對象的方法
     * */
    public SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

    /**
     * 關閉SqlSession的方法
     * */
    public static void close(){
        SqlSession session = threadLocal.get();
        if (session != null){
            session.close();
            threadLocal.set(null);
        }
    }
}

初始化SqlSessionFactory工廠對象:

  • 添加依賴
<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
</dependency>
  • SqlSessionFactoryUtils.java
package com.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {
    private static String RESOURCE = "mybatis-config.xml";
    private static SqlSessionFactory sqlSessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /**
     * 建立一個初始化SqlSessionFactory的方法
     * */
    public static void initSqlSessionFactory(){
        try {
            InputStream is = Resources.getResourceAsStream(RESOURCE);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 獲取工廠對象的方法
     * */
    public SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }

    /**
     * 關閉SqlSession的方法
     * */
    public static void close(){
        SqlSession session = threadLocal.get();
        if (session != null){
            session.close();
            threadLocal.set(null);
        }
    }
}
  • InitSqlSessionListener.java
package com.demo.listener;

import com.demo.utils.SqlSessionFactoryUtils;

import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.annotation.WebListener;

@WebListener
public class InitSqlSessionListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent servletContextEvent){
        System.out.println("容器加載中...");
        // 初始化咱們的SqlSessionFactory對象
        SqlSessionFactoryUtils.initSqlSessionFactory();
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent){
        System.out.println("容器銷燬中...");
        // 關閉Sqlsession對象
        SqlSessionFactoryUtils.close();
    }

}

五、基礎操做——查詢數據

  • 映射配置:sql片斷

  • 映射配置:select配置

    • 特殊配置:字段和屬性不一致時resultMap配置

配置映射:

  • mybatis-config.xml
<mappers>
			 <!-- mapper主要配置引入某一個具體的映射文件,resource進行路徑方式的引入-->
			 <mapper resource="mapper/usersMapper.xml"></mapper>
	 </mappers>
  • usersMapper.xml
<mapper namespace="com.demo.entity.Users">
    <select id="findAll" resultType="com.demo.entity.Users">
        select * from mydb.users
    </select>
</mapper>

用戶查詢DAO編寫:

  • UsersDao.java
package com.demo.dao;
import com.demo.entity.Users;
import com.demo.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;

public class UsersDao {
    private SqlSession sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
    private List<Users> list;

    public List<Users> findAll(){
        try {
            list = sqlSession.selectList("findAll");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return list;
    }
}

servlet層,用於調用DAO的數據:

  • UsersFindServlet.java
package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/index")
public class UsersFindServlet extends HttpServlet {

    private UsersDao usersDAO = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Users> list = usersDAO.findAll();
        req.setAttribute("usersList",list);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}

新建一個JSP頁面,將請求轉發到下一個頁面:

  • home.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    response.sendRedirect("/index");
%>
</body>
</html>

修改web.xml文件,令項目首先訪問home.jsp頁面:

  • 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_3_1.xsd"
         id="WebApp_ID" version="3.1">
    <display-name>mybatispro</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>home.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

引入JSTL依賴:

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
</dependency>

在index.jap頁面遍歷輸出數據:

  • index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>慕課網用戶管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/jquery-3.3.1/jquery-3.3.1.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="page-header">
            <h1>慕課網後臺管理系統 <small>用戶數據管理中心</small></h1>
        </div>
    </div>

    <div class="row">
        <div class="jumbotron">
            <div class="container">
                <h1>MyBatis基礎入門課程!</h1>
                <p>經過一個項目來完成基礎部分的學習</p>
                <p><a class="btn btn-primary btn-lg" href="#" role="button">查看更多,請上慕課網</a></p>
            </div>
        </div>
    </div>

    <div class="row">
        <table class="table table-hover table-striped">
            <tr>
                <th>用戶編號</th>
                <th>登陸賬號</th>
                <th>用戶暱稱</th>
                <th>郵箱</th>
                <th>聯繫方式</th>
                <th>帳號建立時間</th>
                <th>用戶狀態</th>
                <th>操做</th>
            </tr>

            <c:forEach var="user" items="${usersList}">
            <tr>
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.nickname}</td>
                <td>${user.email}</td>
                <td>${user.phone}</td>
                <td>${user.createTime}</td>
                <c:if test="${user.userStatus == 0}">
                    <td>正常</td>
                </c:if>
                <c:if test="${user.userStatus == 1}">
                    <td>鎖定</td>
                </c:if>
                <c:if test="${user.userStatus == 2}">
                    <td>刪除</td>
                </c:if>

                <td>
                    <a href="">查看</a>
                    <a href="">修改</a>
                    <a href="">刪除</a>
                </td>
            </tr>
            </c:forEach>
        </table>
    </div>
</div>
</body>
</html>

啓動TomCat以後,頁面成功顯示數據庫數據,可是在TomCat端能夠看到以下錯誤:

org.apache.ibatis.exceptions.PersistenceException: ###Error querying database. Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed. ###Cause: org.apache.ibatis.executor.ExecutorException: Executor was closed.

緣由多是:

Executor was closed.則頗有多是ibatis的session被關閉了,你這邊若是使用全局變量的service進行操做,因爲session每次獲得dao接口都必須先提交而後關閉,共享service對象致使下一個不可用.

經過一個方法將sqlSession封裝起來:

將UsersDao.java更改以下:

package com.demo.dao;

import com.demo.entity.Users;
import com.demo.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class UsersDao {
    private SqlSession sqlSession;
    private List<Users> list;

    private Users user;

    private SqlSession getSqlSession(){
        sqlSession = SqlSessionFactoryUtils.getSqlSessionFactory().openSession();
        return sqlSession;
    }

    public List<Users> findAll(){
        try {
            list = getSqlSession().selectList("findAll");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return list;
    }

    // 根據id查詢單個用戶
    public Users findById(Integer id){
        try {
            user = getSqlSession().selectOne("findById",id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return user;
    }
}

以後,若是要查看用戶詳細信息,應該怎麼處理呢?

  • UserMapper.xml中添加:
<select id="findById" resultType="com.demo.entity.Users">
        SELECT  * from mydb.users where id = #{id}
</select>
  • 完善UsersDao.java的內容:
private Users user;
// 根據id查詢單個用戶
public Users findById(Integer id){
        try {
            user = sqlSession.selectOne("findById",id);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return user;
}
  • 增長一個查詢用戶的Servlet,UsersFindByIdServlet.java:
package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/detail")
public class UsersFindByIdServlet extends HttpServlet {
    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");

        Users user = usersDao.findById(Integer.parseInt(id));

        req.setAttribute("user",user);
        req.getRequestDispatcher("detail.jsp").forward(req,resp);
    }
}
  • 在index.jsp頁面中進行詳情信息的跳轉配置,訪問某個用戶的來源:
<td>
    <a href="${pageContext.request.contextPath}/detail?id=${user.id}">查看</a>
    <a href="">修改</a>
    <a href="">刪除</a>
</td>
  • 新建立一個目標頁面,detail.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>慕課網用戶管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/jquery-3.3.1/jquery-3.3.1.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="page-header">
            <h1>慕課網後臺管理系統 <small>用戶數據管理中心</small></h1>
        </div>
    </div>

    <c:set var="user" value="${user}"></c:set>


    <div class="row">
        <div class="jumbotron">
            <div class="container">
                <h1>MyBatis基礎入門課程!</h1>
                <p>經過一個項目來完成基礎部分的學習</p>
                <p><a class="btn btn-primary btn-lg" href="#" role="button">查看更多,請上慕課網</a></p>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="col-sm-2 control-label">用戶賬號</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">${user.username}</p>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">登陸密碼</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">*******</p>
                    </div>
                </div>

                <div class="form-group">
                    <label for="nickname" class="col-sm-2 control-label">暱稱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nickname" value="${user.nickname}" name="nickname" placeholder="請輸入暱稱">
                    </div>
                </div>

                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年齡</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="age" value="${user.age}" name="age" placeholder="請輸入年齡">
                    </div>
                </div>

                <div class="form-group">
                    <label for="gender" class="col-sm-2 control-label">性別</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="gender" value="${user.gender}" name="gender" placeholder="請輸入性別">
                    </div>
                </div>

                <div class="form-group">
                    <label for="phone" class="col-sm-2 control-label">聯繫方式</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="phone" name="phone" value="${user.phone}" placeholder="請輸入聯繫方式">
                    </div>
                </div>

                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">郵箱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="email" name="email"  value="${user.email}" placeholder="請輸入郵箱">
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">帳號建立時間</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">${user.createTime}</p>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">最後修改時間</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">${user.updateTime}</p>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">最後登陸時間</label>
                    <div class="col-sm-10">
                        <p class="form-control-static">${user.lastLogin}</p>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label">用戶狀態</label>
                    <div class="col-sm-10">
                        <c:if test="${user.userStatus == 0}">
                            <p class="form-control-static">正常</p>
                        </c:if>
                        <c:if test="${user.userStatus == 1}">
                            <p class="form-control-static">鎖定</p>
                        </c:if>
                        <c:if test="${user.userStatus == 2}">
                            <p class="form-control-static">刪除</p>
                        </c:if>
                    </div>
                </div>

                <div class="form-group">
                    <label for="remark" class="col-sm-2 control-label">備註</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="remark" name="remark"  value="${user.remark}" placeholder="請輸入備註">
                    </div>
                </div>

            </form>
        </div>
    </div>
</div>

</body>
</html>
  • 能夠對時間顯示格式進行修改

引入:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

對顯示時間的地方使用:

<fmt:formatDate value="${user.createTime}" pattern="yyyy-MM-dd"></fmt:formatDate>便可

六、動態SQL語句的配置和使用

若是在查詢條件多的時候,咱們就須要配置多個查詢語句,這顯然不是咱們使用MyBatis想要見到的,MyBatis支持動態SQL語句的使用,於是,咱們能夠對usersMapper.xml進行優化,較少代碼量。

  • usersMapper.xml修改成:
<?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.demo.entity.Users">
    <select id="findAll" resultType="com.demo.entity.Users">
        select * from mydb.users
        <!-- 增長的動態SQL子句 -->
        <if test="id != null">
            where id = #{id}
        </if>
    </select>
</mapper>
  • 一樣的,對UsersDao.java進行改造:
// 根據id查詢單個用戶
    public Users findById(Integer id){
        try {
            user = getSqlSession().selectOne("findAll",id); //這裏傳入了帶有變量的數據
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
        return user;
    }
  • 這個時候若是啓動項目,查看詳細信息的時候,會出現以下錯誤:

###Error querying database. Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer' Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'id' in 'class java.lang.Integer'

這是由於在咱們的映射關係(usersMapper.xml)中,須要一個id,可是這個id是咱們當前命名空間Users給它的提供的一個id,也就是說,在usersMapper.xml修改裏一旦寫了id,是從咱們傳遞進去的對象裏面去提取id這樣一個屬性的,咱們須要改造Users.java,給他增長構造方法。

public Users() {
	 }

public Users(Integer id) {
	this.id = id;
}

以後修改UsersDao.java,將id包裝到Users對象裏交給MyBatis進行處理,MyBatis在usersMapper.xml裏獲取id數據的時候就從users對象裏調用getid()來進行獲取。

七、查詢操做之resultMap配置

若是實體類的屬性和表中的字段屬性不一致的狀況下,應該怎麼去操做??

咱們在前面的基礎上,在Users.java中將登陸賬號從username改成name,並提供name的set和get方法,並將頁面上用於展現的username所有修改成name。

啓動項目後,會發現咱們的其餘信息是正常的,只有用戶賬號(登陸賬號)name是不顯示的(屬性和字段信息不一致)。常規下,咱們的usersMapper.xml中的resultType、Users和咱們的數據庫中的表是按照字段名稱一一對應的。若是出現不一致的狀況,MyBatis就不會對其進行對應關係的配置。就須要咱們手工進行配置。

  • usersMapper.xml
<?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 命令空間,主要進行session級別的緩存管理
 一般狀況,命名空間的值就是當前操做實體類的全名稱(全路徑)-->
<mapper namespace="com.demo.entity.Users">
    <!-- <select id="findUsers" resultType="com.demo.entity.Users"> -->
    <select id="findUsers" resultMap="forUsers">
        select * from mydb.users

        <!-- 增長的動態SQL子句 -->
        <if test="id != null">
            where id = #{id}
        </if>
    </select>
    <!-- 自定義映射關係集合:主要包含一些自定義操做的配置,如不一致的屬性和字段名稱 -->
    <resultMap id="forUsers" type="com.demo.entity.Users">
        <!-- result配置,主要配置普通屬性,column表示配置的是數據庫字段的名稱,property配置的是實體類的屬性名稱 -->
        <result column="username" property="name"></result>
    </resultMap>
</mapper>

八、log4j在MyBatis中的使用

  • 在pom文件中增長依賴
<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
</dependency>
  • 在resource目錄下增長log4j.properties文件
log4j.rootLogger=DEBUG, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p [%t] %37c %3x - %m%n
  • 配置好以後,就可以看到輸出信息(以下所示),便於調試
7935 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Opening JDBC Connection
7935 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.datasource.pooled.PooledDataSource     - Checked out connection 1083949341 from pool.
7936 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@409bc11d]
7937 DEBUG [http-nio-8080-exec-6]       com.demo.entity.Users.findUsers     - ==>  Preparing: select * from mydb.users
7937 DEBUG [http-nio-8080-exec-6]       com.demo.entity.Users.findUsers     - ==> Parameters:
7941 DEBUG [http-nio-8080-exec-6]       com.demo.entity.Users.findUsers     - <==      Total: 3
7942 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@409bc11d]
7942 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@409bc11d]
7942 DEBUG [http-nio-8080-exec-6] org.apache.ibatis.datasource.pooled.PooledDataSource     - Returned connection 1083949341 to pool.
  • 要在servlet中使用應該怎麼使用呢?以對UsersFindByIdServlet.java爲例:
package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;
import org.apache.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/detail")
public class UsersFindByIdServlet extends HttpServlet {

    /**
     * 建立對應的日誌記錄對象
     * 經過不一樣的級別進行日誌的記錄【DEBUG/WARN/INFO/LOG】
     * */
    private Logger log = Logger.getLogger(UsersFindByIdServlet.class);
    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");

        log.info("獲取到查詢參數id-->>"+id);

        Users user = usersDao.findById(Integer.parseInt(id));

        log.info("查詢完成,查詢獲得的數據:"+user);

        req.setAttribute("user",user);
        req.getRequestDispatcher("detail.jsp").forward(req,resp);
    }
}
  • 運行項目,進行查詢,打印輸出信息爲:
20430 INFO  [http-nio-8080-exec-10] com.demo.servlet.UsersFindByIdServlet     - 獲取到查詢參數id-->>1
20441 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Opening JDBC Connection
20441 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.datasource.pooled.PooledDataSource     - Checked out connection 1608755042 from pool.
20441 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5fe3a762]
20442 DEBUG [http-nio-8080-exec-10]       com.demo.entity.Users.findUsers     - ==>  Preparing: select * from mydb.users where id = ?
20443 DEBUG [http-nio-8080-exec-10]       com.demo.entity.Users.findUsers     - ==> Parameters: 1(Integer)
20450 DEBUG [http-nio-8080-exec-10]       com.demo.entity.Users.findUsers     - <==      Total: 1
20450 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5fe3a762]
20451 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.transaction.jdbc.JdbcTransaction     - Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@5fe3a762]
20451 DEBUG [http-nio-8080-exec-10] org.apache.ibatis.datasource.pooled.PooledDataSource     - Returned connection 1608755042 to pool.
20452 INFO  [http-nio-8080-exec-10] com.demo.servlet.UsersFindByIdServlet     - 查詢完成,查詢獲得的數據:Users{id=1, name='xiaoming', userpass='jlujiang', nickname='小明', age=18, gender='男', phone='13565984875', email='4836165@qq.com', createTime=Thu Apr 11 00:00:00 CST 2019, updateTime=null, lastLogin=null, userStatus=0, remark='null'}

九、基礎操做——增長數據(insert增長數據操做及sql片斷配置)

  • 映射配置:sql片斷

  • 映射配置:insert配置

  • usersMapper.xml進行insert配置:

<insert id="addUser" useGeneratedKeys="true" keyProperty="id">
        insert into mydb.users(username, userpass, nickname, age, gender, phone, email, createTime, updateTime, lastLogin, userStatus, remark)
        values (#{name},#{userpass},#{nickname},#{age},#{gender},#{email},#{phone},#{createTime},#{updateTime},#{lastLogin},#{userStatus},#{remark})
</insert>
  • 在Users實體類中先建立構造方法:
public Users(String name, String userpass, String nickname, Integer age, String gender, String phone, String email, Date createTime, Date updateTime, Date lastLogin, Integer userStatus) {
        this.name = name;
        this.userpass = userpass;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
        this.createTime = createTime;
        this.updateTime = updateTime;
        this.lastLogin = lastLogin;
        this.userStatus = userStatus;
    }
  • servlet中調用dao進行數據庫的操做,新建UsersAddServlet.java
package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/addusers")
public class UsersAddServlet extends HttpServlet {

    private UsersDao usersDao = new UsersDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //獲取要添加的數據
        String username = req.getParameter("username");
        String userpass = req.getParameter("userpass");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        //根據用戶數據建立一個用戶對象
        Users user = new Users(username,userpass,nickname,Integer.parseInt(age),gender,email,phone,new Date(),new Date(),new Date(),0);
        //將用戶對象添加到數據庫中
        usersDao.addUser(user);
        //查看剛新增的用戶數據
        resp.sendRedirect("/detail?id="+user.getId());
    }
}
  • 新建添加用戶的頁面addusers.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <title>慕課網用戶管理中心</title>
    <link rel="stylesheet" href="lib/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="lib/jquery-3.3.1/jquery-3.3.1.min.js"></script>
    <script src="lib/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="page-header">
            <h1>慕課網後臺管理系統 <small>用戶數據管理中心</small></h1>
        </div>
    </div>

    <div class="row">
        <div class="jumbotron">
            <div class="container">
                <h1>MyBatis基礎入門課程!</h1>
                <p>經過一個項目來完成基礎部分的學習</p>
                <p><a class="btn btn-primary btn-lg" href="#" role="button">查看更多,請上慕課網</a></p>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <form class="form-horizontal" action="${pageContext.request.contextPath}/addusers">
                <div class="form-group">
                    <label for="username" class="col-sm-2 control-label">用戶賬號</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="username" name="username" placeholder="請輸入用戶賬號">
                    </div>
                </div>

                <div class="form-group">
                    <label for="userpass" class="col-sm-2 control-label">登陸密碼</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="userpass" name="userpass" placeholder="請輸入登陸密碼">
                    </div>
                </div>

                <div class="form-group">
                    <label for="nickname" class="col-sm-2 control-label">暱稱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="nickname" name="nickname" placeholder="請輸入暱稱">
                    </div>
                </div>

                <div class="form-group">
                    <label for="age" class="col-sm-2 control-label">年齡</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="age" name="age" placeholder="請輸入年齡">
                    </div>
                </div>

                <div class="form-group">
                    <label for="gender" class="col-sm-2 control-label">性別</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="gender" name="gender" placeholder="請輸入性別">
                    </div>
                </div>

                <div class="form-group">
                    <label for="phone" class="col-sm-2 control-label">聯繫方式</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="phone" name="phone" placeholder="請輸入聯繫方式">
                    </div>
                </div>

                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">郵箱</label>
                    <div class="col-sm-10">
                        <input type="text" class="form-control" id="email" name="email" placeholder="請輸入郵箱">
                    </div>
                </div>

								<div class="form-group">
                    <input type="submit" value="點擊新增用戶" class="btn btn-primary">
                </div>

            </form>
        </div>
    </div>
</div>
</body>
</html>
  • 接下來,咱們的增長用戶的頁面須要在首頁增長按鈕,跳轉到這個頁面上去,在index.jsp中
<p><a class="btn btn-primary btn-lg" href="${pageContext.request.contextPath}/addusers.jsp" role="button">新增用戶</a></p>

十、基礎操做——更新操做(update配置及set動態語句操做)

  • 映射配置:update配置

  • 動態SQL配置:set配置

  • 在用戶詳情頁進行信息的修改,detail.jsp中添加:

對from表單添加:
	action="${pageContext.request.contextPath}/updateusers"
添加按鈕:
	<div class="form-group">
    	<input type="submit" value="提交數據更新" class="btn btn-primary">
	</div>
  • 映射文件usersMapper.xml中添加映射
<update id="updateUser">
        update mydb.users set username = #{name},
                              userpass = #{userpass},
                              nickname = #{nickname},
                              age = #{age},
                              gender = #{gender},
                              email = #{email},
                              phone = #{phone},
                              createTime = #{createTime},
                              updateTime = #{updateTime},
                              lastLogin = #{lastLogin},
                              userStatus = #{userStatus},
                              remark = #{remark}
        where id = #{id}
    </update>
  • 在DAO中增長調用配置,UsersDao.java:
// 用於修改用戶資料的方法
	 public Users updateUser(Users user){
			 try {
					 //返回值:是insert執行過程當中影響的行數
					 getSqlSession().update("updateUser",user);
					 sqlSession.commit();
			 }catch (Exception e){
					 e.printStackTrace();
			 }finally {
					 sqlSession.close();
			 }
			 return user;
	 }
  • 增長一個Servlet專門用於用戶修改,UsersUpdateServlet.java

事先須要獲取更新的用戶的id用來進行更改,就須要在修改頁面增長一個隱藏域,用來獲取用戶id。

input type="hidden" name="id" value="${user.id}"

package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@WebServlet("/updateusers")
public class UsersUpdateServlet extends HttpServlet {

    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 獲取用戶要更新的數據
        String id = req.getParameter("id");
        String nickname = req.getParameter("nickname");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String remark = req.getParameter("remark");
        // 建立用戶對象
        Users user = new Users(Integer.parseInt(id),nickname,Integer.parseInt(age),gender,phone,email,new Date(),remark);
        // 提交更新
        usersDao.updateUser(user);
        //查看更新後的數據
        resp.sendRedirect("/detail?id="+user.getId());
    }
}

須要在Users.java中添加更新操做是對應的構造函數:

public Users(Integer id, String nickname, Integer age, String gender, String phone, String email, Date updateTime, String remark) {
        this.id = id;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.phone = phone;
        this.email = email;
        this.updateTime = updateTime;
        this.remark = remark;
    }

這時候啓動項目,進行數據修改,可是修改失敗,後臺提示:

Error updating database. Cause: java.sql.SQLIntegrityConstraintViolationException: Column 'username' cannot be null

這裏提示username不能爲null,可是咱們並無更新username,爲何會提示這裏出錯呢?其實緣由是在usersMapper.xml的update操做的時候,設置了username = #{name},可是咱們建立的用戶對象又沒有包含這個屬性,就會設置爲null了,因此在update操做的不能使用這種語句,應該使用動態SQL語句。

將usersMapper.xml中的update語句修改成:

<update id="updateUser">
        update mydb.users
        <set>
            <if test="name != null">username = #{name},</if>
            <if test="userpass != null">userpass = #{userpass},</if>
            <if test="nickname != null">nickname = #{nickname},</if>
            <if test="age != null">age = #{age},</if>
            <if test="gender != null">gender = #{gender},</if>
            <if test="email != null">email = #{email},</if>
            <if test="phone != null">phone = #{phone},</if>
            <if test="createTime != null">createTime = #{createTime},</if>
            <if test="updateTime != null">updateTime = #{updateTime},</if>
            <if test="lastLogin != null">lastLogin = #{lastLogin},</if>
            <if test="userStatus != null">userStatus = #{userStatus},</if>
            <if test="remark != null">remark = #{remark},</if>
        </set>
        where id = #{id}
</update>

十一、基礎操做——刪除數據(delete刪除數據及項目中的帳號鎖定操做)

  • 映射配置:delete配置

  • 補充:業務功能中的刪除賬號、鎖定賬號和完全刪除帳號

  • 首先修改index.jsp頁面中的刪除anniu

<td>
    <a href="${pageContext.request.contextPath}/detail?id=${user.id}">查看</a>
    <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=lock">鎖定</a>
    <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=del">刪除</a>
</td>
  • 在usersMapper.xml中增長delete配置
<delete id="delUser">
		delete from mydb.users where id = #{id}
</delete>
  • 在Dao中(UsersDao.java)增長配置
// 根據id進行刪除
    public void delUsers(Integer id){
        try {
            //返回值:是insert執行過程當中影響的行數
            getSqlSession().delete("delUser",id);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sqlSession.close();
        }
    }
  • 補充:解鎖和鎖定功能,修改index.jsp頁面

執行刪除/鎖定操做:update操做 鎖定: 鎖定的用戶進行標註解鎖 沒鎖定的用戶進行標註鎖定

<td>
        <a href="${pageContext.request.contextPath}/detail?id=${user.id}">查看</a>
        <c:if test="${user.userStatus == 0}">
            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=lock">鎖定</a>
        </c:if>
        <c:if test="${user.userStatus == 1}">
            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=uplock">解鎖</a>
        </c:if>
            <a href="${pageContext.request.contextPath}/deluser?id=${user.id}&type=del">刪除</a>
        </td>
  • 接下來開發servlet,命名爲UsersDelServlet.java:
package com.demo.servlet;

import com.demo.dao.UsersDao;
import com.demo.entity.Users;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/deluser")
public class UsersDelServlet extends HttpServlet {

    private UsersDao usersDao = new UsersDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //獲取參數
        String id = req.getParameter("id");
        String type = req.getParameter("type");
        //執行刪除或鎖定
        if ("lock".equals(type)){
            // 執行鎖定操做:update操做
            // 鎖定的用戶進行標註解鎖
            // 沒鎖定的用戶進行標註鎖定
            Users user = new Users();
            user.setId(Integer.parseInt(id));
            user.setUserStatus(1);

            usersDao.updateUser(user);

        }else if ("del".equals(type)){
            // 執行刪除操做:delete操做
            usersDao.delUsers(Integer.parseInt(id));
        }else if ("unlock".equals(type)){
            // 解鎖
            Users user = new Users();
            user.setId(Integer.parseInt(id));
            user.setUserStatus(0);

            usersDao.updateUser(user);
        }
        //跳轉到首頁
        resp.sendRedirect("/index");
    }
}
相關文章
相關標籤/搜索