SpringBoot整合Mybatis對單表的增、刪、改、查操作

来源:https://www.cnblogs.com/south-wood/archive/2020/03/07/12436978.html
-Advertisement-
Play Games

一.目標 SpringBoot整合Mybatis對單表的增、刪、改、查操作 二.開發工具及項目環境 IDE: IntelliJ IDEA 2019.3 SQL: Navicat for MySQL 三.基礎環境配置 1. 創建資料庫: demodb 2. 創建數據表及插入數據 3. 必備Maven依 ...


一.目標

SpringBoot整合Mybatis對單表的增、刪、改、查操作


二.開發工具及項目環境

  • IDE: IntelliJ IDEA 2019.3

  • SQL:Navicat for MySQL


三.基礎環境配置

  1. 創建資料庫:demodb

  2. 創建數據表及插入數據

    DROP TABLE IF EXISTS t_employee;
    CREATE TABLE t_employee (
      id int PRIMARY KEY AUTO_INCREMENT COMMENT '主鍵編號',
      name varchar(50) DEFAULT NULL COMMENT '員工姓名',
      sex varchar(2) DEFAULT NULL COMMENT '員工性別',
      phone varchar(11) DEFAULT NULL COMMENT '電話號碼'
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    INSERT INTO t_employee VALUES ('1', '張三豐', '男', '13812345678');
    INSERT INTO t_employee VALUES ('2', '郭靖', '男', '18898765432');
    INSERT INTO t_employee VALUES ('3', '小龍女', '女', '13965432188');
    INSERT INTO t_employee VALUES ('4', '趙敏', '女', '15896385278');
    
  3. 必備Maven依賴如下:

    <!--        MySQL依賴-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
                <version>5.1.48</version>
            </dependency>
    
    <!--        Thymleaf依賴-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
    <!--        mybatis依賴-->
       <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
  4. 添加配置文件,可用使用yaml配置,即application.yml(與application.properties配置文件,沒什麼太大的區別)連接池的配置如下:

    spring:
      ##連接資料庫配置
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        ##jdbc:mysql://(ip地址):(埠號)/(資料庫名)?useSSL=false
        url: jdbc:mysql://localhost:3306/demodb?useUnicode=true&useSSL=false&characterEncoding=UTF8
        ##資料庫登錄名
        data-username: root
        ##登陸密碼
        data-password:
    
      ##靜態資源的路徑
      resources:
        static-locations=classpath:/templates/
    
  5. 測試配置情況

    在java的com包中,新建包controller,在包中創建控制器類:==EmployeeController==

    @Controller
    public class EmployeeController{
    //測試使用
    @GetMapping("/test")
    //註解:返回JSON格式
    @ResponseBody
    public String test() {
    return "test";
    }
    }

    啟動主程式類,在瀏覽器中輸入:http://localhost:8080/test


四.開始編寫

  1. 編寫ORM實體類

    在java的com包中,新建包domain,在包中創建實體類:Employee

    public class Employee {
        private Integer id;   //主鍵
        private String name;  //員工姓名
        private String sex;   //員工性別
        private String phone; //電話號碼
    
        }

    ==不要忘記封裝==

  2. 完成mapper層==增刪改查==編寫

    在java的com包中,新建包mapper,在包中創建Mapper介面文件:EmployeeMapper

    //表示該類是一個MyBatis介面文件
    @Mapper
    //表示具有將資料庫操作拋出的原生異常翻譯轉化為spring的持久層異常的功能
    @Repository
    public interface EmployeeMapper {
        //根據id查詢出單個數據
        @Select("SELECT*FROM t_employee WHERE id=#{id}")
        Employee findById(Integer id);
    
        //查詢所有數據
        @Select("SELECT * FROM t_employee")
        public List<Employee> findAll();
    
        //根據id修改數據
        @UpdateProvider(type = EmployeeMapperSQL.class,method = "updateEmployee")
        int updateEmployee(Employee employee);
    
        //添加數據
        @Insert("INSERT INTO t_employee(name,sex,phone)  values(#{name},#{sex},#{name})")
        public int inserEm(Employee employee);
    
        //根據id刪除數據
        @Delete("DELETE FROM t_employee WHERE id=#{id}")
        public int deleteEm(Integer id);
    }
    
  3. 完成service層編寫,為controller層提供調用的方法

    1. 在java的com包中,新建包service,在包中創建service介面文件:EmployeeServic

         ```java
        public interface EmployeeService {
            //查詢所有員工對象
            List<Employee> findAll();
            //根據id查詢單個數據
            Employee findById(Integer id);
            //修改數據
            int updateEmployee(Employee employee);
            //添加數據
            int addEmployee(Employee employee);
            //刪除
            int deleteEmployee(Integer id);
        }
    2. 在service包中,新建包impl,在包中創建介面的實現類:EmployeeServiceImpl

      @Service
      //事物管理
      @Transactional
      public class EmployeeServiceImpl implements EmployeeService {
          //註入EmployeeMapper介面
          @Autowired
          private EmployeeMapper employeeMapper;
          //查詢所有數據
          public List<Employee> findAll() {
              return employeeMapper.findAll();
          }
      
          //根據id查詢單個數據
          public Employee findById(Integer id) {
              return employeeMapper.findById(id);
          }
      
          //修改數據
          public int updateEmployee(Employee employee) {
              return employeeMapper.updateEmployee(employee);
          }
      
          //添加
          public int addEmployee(Employee employee) {
              return employeeMapper.inserEm(employee);
          }
      
          //根據id刪除單個數據
          public int deleteEmployee(Integer id) {
              return employeeMapper.deleteEm(id);
          }
      }
  4. 完成Controller層編寫,調用serivce層功能,響應頁面請求

    在先前創建的controller.EmployeeController中編寫方法

    @Controller
    public class EmployeeController {
    
        @Autowired
        private EmployeeService employeeService;
    
    //主頁面  
        //響應查詢所有數據,然後顯示所有數據
        @GetMapping("/getall")
        public String getAll(Model model) {
            List<Employee> employeeList = employeeService.findAll();
            model.addAttribute("employeeList", employeeList);
            return "showAllEmployees";
        }
    
    //修改頁面
        //響應到達更新數據的頁面
        @GetMapping("/toUpdate/{id}")
        public String toUpdate(@PathVariable Integer id, Model model){
            //根據id查詢
            Employee employee=employeeService.findById(id);
            //修改的數據
            model.addAttribute("employee",employee);
            //跳轉修改
            return "update";
        }
    
        //更新數據請求並返回getall
        @PostMapping("/update")
        public String update(Employee employee){
            //報告修改
            employeeService.updateEmployee(employee);
            return "redirect:/getall";
        }
    
    //刪除功能
        //響應根據id刪除單個數據,然後顯示所有數據
        @GetMapping("/delete/{id}")
        public String delete(@PathVariable Integer id){
            employeeService.deleteEmployee(id);
            return "redirect:/getall";
        }
    
    //添加頁面
        //添加數據
        @PostMapping("/add")
        public String addEmployee(Employee employee){
            employeeService.addEmployee(employee);
            return "redirect:/getall";
        }
    }

五.編寫前端

  1. 主頁面

    在resouces的templates中,創建主頁面:addEmployee.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.prg">
    <head>
        <meta charset="UTF-8">
        <title>添加員工信息</title>
    </head>
    <body>
    <h2>添加員工信息</h2>
    <form action="/add" method="post">
        姓名:<input type="text" name="name"><br>
        性別:<input type="radio" value="男" name="sex" checked="checked">男
        <input type="radio" value="女" name="sex" >女<br>
        電話:<input type="text" name="phone"><br>
        <input type="submit" value="添加">
    </form>
    </body>
    </html>

    註意<html lang="en" ==xmlns:th="http://www.thymeleaf.prg"==>

  2. 修改頁面

    resouces的templates中,創建修改頁面:update.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>修改信息</title>
    </head>
    <body>
    <h2>修改信息</h2>
    <form th:action="@{/update}" th:object="${employee}" method="post">
        <input th:type="hidden" th:value="${employee.id}" th:field="*{id}">
        姓名:<input th:type="text" th:value="${employee.name}" th:field="*{name}"><br>
        性別:<input th:type="radio" th:value="男" th:checked="${employee.sex=='男'}" th:field="*{sex}">男
        <input th:type="radio" th:value="女" th:checked="${employee.sex=='女'}" th:field="*{sex}">女<br>
        電話:<input th:type="text" th:value="${employee.phone}" th:field="*{phone}"><br>
        <input th:type="submit" value="更新">
    </form>
    
    </body>
    </html>
  3. 添加頁面

    resouces的templates中,創建添加頁面:addEmployee.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.prg">
    <head>
        <meta charset="UTF-8">
        <title>添加員工信息</title>
    </head>
    <body>
    <h2>添加員工信息</h2>
    <form action="/add" method="post">
        姓名:<input type="text" name="name"><br>
        性別:<input type="radio" value="男" name="sex" checked="checked">男
        <input type="radio" value="女" name="sex" >女<br>
        電話:<input type="text" name="phone"><br>
        <input type="submit" value="添加">
    </form>
    </body>
    </html>

    啟動主程式類,在瀏覽器中輸入:http://localhost:8080/getall


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.PHP語法基礎是否都會,比如異常捕捉,面向對象,數組操作語法,字元串操作,cookie,session,全局變數,超全局數組,防止sql註入,mysql預處理 2.MYSQL基礎語法,欄位設計,原生sql語句,如何優化查詢效率,索引如何使用,分組聚合,表關聯(一對多,多對多),分庫分表, 3.服 ...
  • 如何使用python將大量數據導出到Excel中的小技巧 (1) 問題描述:為了更好地展示數據,Excel格式的數據文件往往比文本文件更具有優勢,但是具體到python中,該如何導出數據到Excel呢?如果碰到需要導出大量數據又該如何操作呢?本文主要解決以上兩個問題。 PS註意:很多人學Python ...
  • 視頻地址:https://www.bilibili.com/video/av59676843/?p=631 課件、源碼及習題:鏈接:https://pan.baidu.com/s/1Jt59yZfuK-4j7sYZgzmUqA 提取碼:yz8l 習題答案:https://www.cnblogs.co ...
  • 1、Mac下安裝requests庫: pip3 install requests 2、requests庫的使用 2.1 發送請求 使用Requests發送網路請求第一步,導入requests模塊: import requests 嘗試獲取某個網頁。如百度首頁: r = requests.get('h ...
  • 1. 起因 ​ 使用springboot也有些時間,一直很好奇它如何做到自動配置的,所以查閱了相關資料並且學習了相關內容,才寫了這篇文章。 2. 分析 ​ ①第一步我們從它的啟動配置類(XxxApplication)收起,我們進入到他的@SpringBootApplication註解。 ​ ②我們可 ...
  • 曾有邪教稱1999年12月31日是世界末日,當然該謠言已經不攻自破。 還有人稱今後的某個世紀末的12月31日,如果是星期一則會..…. 有趣的是,任何一個世紀末的年份的12月31日都不可能是星期一!!! 於是,“謠言製造商”又修改為星期日...... 1999年的12月31日是星期五,請問:未來哪一 ...
  • 前言 我們都知道redis是常駐在記憶體當中的,因此他的效率比MySQL要快很多很多。但又引發了另外一個問題,記憶體從本質上講,它是昂貴的,不能用於大量的長時間的存儲,他是“不安全不穩定的“,並且有可能存在記憶體泄露,不能與磁碟相比。 那麼如果解決這種問題呢?因此我們使用redis的時候,強制的應該給每個 ...
  • 一.前言 在講解 str / bytes /unicode區別之前首先要明白位元組和字元的區別,請參考:bytearray/bytes/string區別 中對位元組和字元有清晰的講解,最重要是明白: 字元str是給人看的,例如:文本保存的內容,用來操作的; 位元組bytes是給電腦看的,例如:二進位數據 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...