Springboot-增刪改查


1.使用Mysql建立一張表

  • 主要字段包括學院代碼、學院名稱、院長姓名、院長工號等

2.項目結構

3.進行配置Spring boot,連接到Mysql

  • 對pom.xml依賴進行導入
  • 使用阿里巴巴開源的druid的數據庫連接池進行鏈接
  • 將application.properties文件重命名為application.yml
  • 在application.yml配置數據庫的信息
server:
  port: 8881
  servlet:
    context-path: /ex02
spring:
  datasource:
    name: druidDataSource
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    #自己的數據庫Ip地址和數據庫名,賬號及密碼
    url: jdbc:mysql://localhost:3306/college?useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC
    username: root
    password: 99150704
    druid:
      #監控統計攔截的過濾器 不加監控界面sql無法統計 wall用於防火牆
      filters: stat,wall,log4j,config
      #最大連接數
      max-active: 100
      #初始化大小
      initial-size: 1
      #獲取連接最大等待時間
      max-wait: 60000
      min-idle: 1
      #間隔多久檢測一次需要關閉的空閑連接 毫秒
      time-between-eviction-runs-millis: 60000
      #連接在連接池中最小生存的時間,毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: select 'x'
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 50
      max-pool-prepared-statement-per-connection-size: 20
      web-stat-filter:
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        url-pattern: /*
      stat-view-servlet:
        #白名單IP
        allow: 127.0.0.1
        #黑名單IP
        deny: 192.168.0.106
        #登錄賬號和密碼
        login-username: ex02
        login-password: springboot
        #啟用重置數據功能
        reset-enable: true
  jpa:
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
  thymeleaf:
    cache: false
    suffix: .html
    encoding: UTF-8
    servlet:
      content-type: text/html
    mode: HTML5

  • pom.xml配置:
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>1.9.22</version>
        </dependency>

<!-- 數據庫連接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
  • 在resources文件夾下添加log4j.properties的屬性文件,避免報錯,內容如下
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p - %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=firestorm.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
  • 啟動項目,訪問druid控制台
    • 賬號、密碼為配置文件設置的


4.使用JPA+postman進行增刪改查數據

  • 使用idea中的datasource連接mysql數據庫
    • JPA可以利用這個自動完成數據源的實體類的映射

①新建實體類包,映射的實體類代碼如下:

package com.example.sw_ex02.entity;

import com.fasterxml.jackson.annotation.JsonProperty;

import javax.persistence.*;
import java.util.Objects;

@Entity
@Table(name = "college", schema = "college", catalog = "")
public class CollegeEntity {
    private String collegeCode;
    private String collegeName;
    private String deanName;
    private String deanNumber;

    @Id
    @Column(name = "college_code")
    public String getCollegeCode() {
        return collegeCode;
    }
    //springboot解析器在解析json過程中出現問題,因字段名駝峰命名無法匹配字段名導致,進行注解添加
    @JsonProperty(value = "college_code")
    public void setCollegeCode(String collegeCode) {
        this.collegeCode = collegeCode;
    }

    @Basic
    @Column(name = "college_name")
    public String getCollegeName() {
        return collegeName;
    }
    @JsonProperty(value = "college_name")
    public void setCollegeName(String collegeName) {
        this.collegeName = collegeName;
    }

    @Basic
    @Column(name = "dean_name")
    public String getDeanName() {
        return deanName;
    }
    @JsonProperty(value = "dean_name")
    public void setDeanName(String deanName) {
        this.deanName = deanName;
    }

    @Basic
    @Column(name = "dean_number")
    public String getDeanNumber() {
        return deanNumber;
    }
    @JsonProperty(value = "dean_number")
    public void setDeanNumber(String deanNumber) {
        this.deanNumber = deanNumber;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CollegeEntity that = (CollegeEntity) o;
        return Objects.equals(collegeCode, that.collegeCode) &&
                Objects.equals(collegeName, that.collegeName) &&
                Objects.equals(deanName, that.deanName) &&
                Objects.equals(deanNumber, that.deanNumber);
    }

    @Override
    public int hashCode() {
        return Objects.hash(collegeCode, collegeName, deanName, deanNumber);
    }
}

②新建Repository包,創建CollegeRepository接口

package com.example.sw_ex02.repository;

import com.example.sw_ex02.entity.CollegeEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CollegeRepository extends JpaRepository<CollegeEntity,String> {
}

③編寫CollegeService層方法,實現增刪改查的業務邏輯實現

package com.example.sw_ex02.service;

import com.example.sw_ex02.entity.CollegeEntity;
import com.example.sw_ex02.repository.CollegeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollegeServiceImpl {

    @Autowired
    private CollegeRepository collegeRepository;

    /***
     * @description 查詢所有用戶
     */
    public List<CollegeEntity> getCollegeList(){
        return collegeRepository.findAll();
    }

    /***
     * @description 查詢單個用戶
     */
    public CollegeEntity getCollege(String code){
        return collegeRepository.findById(code).get();
    }

    /***
     * @description 創建用戶
     */
    public CollegeEntity insertCollege(CollegeEntity collegeEntity){
        collegeEntity.setCollegeCode("");
        collegeEntity.setCollegeName("");
        collegeEntity.setDeanName("");
        collegeEntity.setDeanNumber("");
        return collegeRepository.save(collegeEntity);
    }

    /***
     * @description 修改用戶
     */
    public CollegeEntity updateCollege(CollegeEntity collegeEntity){
        CollegeEntity collegeEntity1=collegeRepository.findById(collegeEntity.getCollegeCode()).get();

        if(collegeEntity1==null){
            return null;
        }

        collegeEntity1.setCollegeName(collegeEntity.getCollegeName());
        collegeEntity1.setDeanNumber(collegeEntity.getDeanNumber());
        collegeEntity1.setDeanName(collegeEntity.getDeanName());

        return collegeRepository.save(collegeEntity1);
    }

    /***
     * @description 刪除用戶
     */
    public boolean deleteCollege(String code){
        try {
            collegeRepository.deleteById(code);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}

④編寫CollegeController,實現數據的增刪改查

package com.example.sw_ex02.controller;

import com.example.sw_ex02.entity.CollegeEntity;
import com.example.sw_ex02.service.CollegeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("college")
public class CollegeController {

    @Autowired
    private CollegeServiceImpl collegeService;

    /***
     * @description 查詢所有用戶
     */
    @GetMapping
    public List<CollegeEntity> getAllCollege(){
        return collegeService.getCollegeList();
    }

    /***
     * @description 查詢單個用戶
     */
    @GetMapping("{code}")
    public CollegeEntity getCollege(@PathVariable("code")String code){
        return collegeService.getCollege(code);
    }

    /***
     * @description 創建用戶
     */
    @PostMapping
    public CollegeEntity insertCollege(@RequestBody CollegeEntity collegeEntity){
       return collegeService.insertCollege(collegeEntity);
    }

    /***
     * @description 修改用戶
     */
    @PatchMapping
    public CollegeEntity updateCollege(@RequestBody CollegeEntity collegeEntity){
        return collegeService.updateCollege(collegeEntity);
    }

    /***
     * @description 刪除用戶
     */
    @DeleteMapping("{code}")
    public boolean deleteCollege(@PathVariable("code")String code){
        collegeService.deleteCollege(code);
        return true;
    }
}

⑤啟動驗證

  • 在啟動類上面添加JPA注解,啟動項目
    • 顯示數據庫的內容,並可以依據url后綴的不同進行數據查詢
  • 使用postman接口測試工具調用api接口對數據進行刪除、添加、修改
    • :注意數據的傳送格式
    • 修改:注意數據的傳送格式
    • 刪除

⑥問題小結

  • spring boot對Json數據的轉換存在問題,會將返回的數據轉換成null,在實體類中添加注解即可解決

4.使用模板引擎進行數據的增刪改查

①使用idea連接數據庫,進行映射創建實體類

②編寫增刪改查的業務邏輯代碼

③在目錄/resources下創建文件夾tempates,添加html文件,list頁面、toAdd頁面、toEdit頁面,進行網頁的增刪改查

  • list頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>userList</title>
    <!--thymeleaf表達式,th:href="@{/css/bootstrap.css}"@表示后面的是一個鏈接-->
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
</head>
<body class="container">
<br/>
<h1>用戶列表</h1>
<br/><br/>
<div class="with:80%">
    <table class="table table-hover">
        <thead>
        <tr>
            <th>#</th>
            <th>college_code</th>
            <th>college_name</th>
            <th>dean_name</th>
            <th>dean_number</th>
            <th>Edit</th>
            <th>Delete</th>
        </tr>
        </thead>
        <tbody>
        <!--each來進行for循環求值-->
        <tr  th:each="collegeEntity : ${collegeEntites}">
            <th scope="row" th:text="${collegeEntity.collegeCode}">1</th>
            <td th:text="${collegeEntity.collegeCode}">neo</td>
            <td th:text="${collegeEntity.collegeName}">neo</td>
            <td th:text="${collegeEntity.deanName}">Otto</td>
            <td th:text="${collegeEntity.deanNumber}">6</td>
            <td><a th:href="'/ex02/toEdit/'+${collegeEntity.collegeCode}">edit</a></td>
            <td><a th:href="'/ex02/delete/'+${collegeEntity.collegeCode}">delete</a></td>
        </tr>
        </tbody>
    </table>
</div>
<div class="form-group">
    <div class="col-sm-2 control-label">
        <a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
    </div>
</div>

</body>
</html>
  • toAdd頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>college</title>
    <!--利用thymeleaf表達式獲取css路徑,bootstrap給button提供樣式-->
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
</head>
<body class="container">
<br/>
<h1>增加數據</h1>
<br/><br/>
<div class="with:80%">
    <form class="form-horizontal"   th:action="@{/edit}"  method="post">
        <div class="form-group">
            <label for="collegeCode" class="col-sm-2 control-label">collegeCode</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="collegeCode"  id="collegeCode"  placeholder="collegeCode"/>
            </div>
        </div>
        <div class="form-group">
            <label for="collegeName" class="col-sm-2 control-label" >collegeName</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="collegeName" id="collegeName"  placeholder="collegeName"/>
            </div>
        </div>
        <div class="form-group">
            <label for="deanName" class="col-sm-2 control-label">deanName</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="deanName"  id="deanName" placeholder="deanName"/>
            </div>
        </div>
        <div class="form-group">
            <label for="deanNumber" class="col-sm-2 control-label">deanNumber</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="deanNumber"  id="deanNumber"  placeholder="deanNumber"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="Submit" class="btn btn-info" />
                &nbsp; &nbsp; &nbsp;
                <input type="reset" value="Reset" class="btn btn-info" />
            </div>

        </div>
    </form>
</div>
</body>
</html>
  • toEdit頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>college</title>
    <link rel="stylesheet" th:href="@{/css/bootstrap.css}"/>
</head>
<body class="container">
<br/>
<h1>修改用戶</h1>
<br/><br/>
<div class="with:80%">
    <form class="form-horizontal"   th:action="@{/edit}" th:object="${college}"  method="post">
        <input type="hidden" name="collegeCode" th:value="*{collegeCode}" />

        <div class="form-group">
            <label for="collegeName" class="col-sm-2 control-label" >collegeName</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="collegeName" id="collegeName"  th:value="*{collegeName}" placeholder="collegeName"/>
            </div>
        </div>
        <div class="form-group">
            <label for="deanName" class="col-sm-2 control-label">deanName</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="deanName"  id="deanName" th:value="*{deanName}" placeholder="deanName"/>
            </div>
        </div>
        <div class="form-group">
            <label for="deanNumber" class="col-sm-2 control-label">deanNumber</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" name="deanNumber"  id="deanNumber" th:value="*{deanNumber}" placeholder="deanNumber"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <input type="submit" value="Submit" class="btn btn-info" />
                &nbsp; &nbsp; &nbsp;
                <a href="/list" th:href="@{/list}" class="btn btn-info">Back</a>
            </div>

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

④編寫CollegeController,實現數據的增刪改查

package com.example.sw_ex02.controller;

import com.example.sw_ex02.entity.CollegeEntity;
import com.example.sw_ex02.service.CollegeServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class CollegeControllerThymeleaf {

    @Resource
    CollegeServiceImpl collegeService;

    /***
     * @description 將"/"自動重定向到"/list"
     * @return 跳轉到‘/list’頁面
     */
    @RequestMapping("/thymeleaf")
    public String index(){
        return "redirect:/list";
    }

    /***
     * @description 將"/"自動重定向到"/list"
     * @return 跳轉到‘/list’頁面
     */
    @RequestMapping("/list")
    public String list(Model model){
        List<CollegeEntity> collegeEntities=collegeService.getCollegeList();
        model.addAttribute("collegeEntites",collegeEntities);
        return "college/list";
    }

    /*
     * @Discription:跳轉到增加用戶頁面
     */
    @RequestMapping(value = "/toAdd")
    public String toAdd(){
        return "college/collegeAdd";
    }

    /*
     * @param  "/add"鏈接
     * @return  重定向到/list頁面
     * @Discription: 保存實體到數據庫,然后返回到list界面
     */
    @RequestMapping(value = "/add")
    public String add(CollegeEntity collegeEntity){
        collegeService.save(collegeEntity);
        return "redirect:/list";
    }

    /*
     * @param  /toEdit鏈接進入該程序
     * @return 查詢出數據以后,跳轉到編輯界面
     * @Discription:跳轉到編輯頁面對數據進行編輯
     */
    @RequestMapping(value="/toEdit/{code}")
    public String toEdit(Model model,@PathVariable("code")String code) {
        CollegeEntity collegeEntity = collegeService.findCollegeById(code);
        model.addAttribute("college", collegeEntity);
        return "college/collegeEdit";
    }

    /*
     * @param  "/edit"鏈接進入該程序
     * @return 重定向到"/list"鏈接
     * @Discription:更新數據庫中的數據以后跳轉到list
     */
    @RequestMapping(value = "/edit")
    public String edit(CollegeEntity collegeEntity){
        collegeService.edit(collegeEntity);
        return "redirect:/list";
    }

    /*
     * @param  "/delete"鏈接進入該方法
     * @return  重定向到"/list"
     * @Discription: 刪除某一個數據后定向到"/list"
     */
    @RequestMapping(value="/delete/{code}")
    public String delete(@PathVariable("code")String code){
        collegeService.delete(code);
        return "redirect:/list";
    }
}

⑤啟動驗證

  • 在瀏覽器輸入相應url,頁面顯示數據庫中表的數據,在網頁上對表進行增刪改查

⑥問題小結

  • 在進行模板引擎進行增刪改查的時候,要注意鏈接的正確
  • 注意GET與POST請求的區別
    • GET - 從指定的資源請求數據
    • POST - 向指定的資源提交要被處理的數據
  • 了解@RequestMapping注解
    • 設置請求地址
    • 設置請求的類型,依據請求類型的不同,函數進行不同的操作

5.mybatis-數據庫查詢

①進行mybatis的配置

  • 在pom.xml中進行依賴導入
<!-- mybatis 集成 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- mybatis自動生成插件 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
        <!-- mybatis自動分頁插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.10</version>
        </dependency>
  • 在appolication.yml中進行配置
#mybatis
mybatis:
  type-aliases-package: com.example.sw_ex02.entity
  mapper-locations: com.example.sw_ex02.Mapper/*.xml
  configuration:
    map-underscore-to-camel-case: true
#配置控制台打印日志Debug,用來查看sql寫沒寫錯
logging:
  level:
    com.jd.mapper: debug

②依據前面所述導入實體類

③在com.example.xxx下創建Mapper文件夾

  • 依據需求創建接口xxxx,在接口中聲明相應的函數
package com.example.sw_ex02.Mapper;

import com.example.sw_ex02.entity.CollegeEntity;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface CollegeMapper {
    List<CollegeEntity> getAllCollege();
}

  • 創建xxxx(與接口文件名字相同).xml文件,在該文件中,使用SQL語句進行對接口文件中的函數進行相應的實現
<?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.example.sw_ex02.Mapper.CollegeMapper">
    <select id="getAllCollege" resultType="com.example.demo.entity.CollegeEntity">
        select * from college;
    </select>
</mapper>

④在service文件夾下創建相關的邏輯業務實現

package com.example.sw_ex02.service;

import com.example.sw_ex02.Mapper.CollegeMapper;
import com.example.sw_ex02.entity.CollegeEntity;
import com.example.sw_ex02.repository.CollegeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CollegeServiceImpl {

    @Autowired(required = false)
    private CollegeMapper collegeMapper;

    //mybatis-查詢數據
    public List<CollegeEntity> ListCollege(){
        return collegeMapper.getAllCollege();
    }
}

⑤在conrtoller下創建文件,實現xxxxController,進行數據的操作

package com.example.sw_ex02.controller;

import com.example.sw_ex02.service.CollegeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mybatis")
public class CollegeControllerMybatis {

    @Autowired
    private CollegeServiceImpl collegeService;

    @RequestMapping("/all")
    public String getAllCollege(){
        return collegeService.ListCollege().toString();
    }
}

⑧啟動驗證,輸入url進行驗證

6.小結

  • 由上述三種方法,個人感覺使用模板引擎較為方便


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM