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

一.目標

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


二.開發工具及項目環境

  • IDE: IntelliJ IDEA 2019.3前端

  • SQL:Navicat for MySQLjava


三.基礎環境配置

  1. 建立數據庫:demodbmysql

  2. 建立數據表及插入數據spring

    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依賴以下:sql

    <!--        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==mybatis

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

    啓動主程序類,在瀏覽器中輸入:http://localhost:8080/testapp


四.開始編寫

  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

相關文章
相關標籤/搜索