欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java之SpringBoot實現(xiàn)基本增刪改查(前后端分離版)

 更新時間:2023年03月30日 09:21:21   作者:Fish_Vast  
這篇文章主要介紹了Java中SpringBoot如何實現(xiàn)基本的增刪改查,前后端分離版,沒有和前端進行聯(lián)系,感興趣的小伙伴可以借鑒閱讀本文

根據(jù)上圖所示,idea中我們有7個比較重要的模塊需要建立

(1)controller包:如果學習過或者對SpringMVC有所了解的小伙伴,肯定知道,controller是控制層,相當于我們的接收瀏覽器信息并響應發(fā)送相關(guān)信息的地方,具體的還結(jié)合計算機網(wǎng)絡相關(guān)知識,了解在瀏覽器中如何接收信息,并如何響應信息,在controller控制層下我們實現(xiàn)相關(guān)數(shù)據(jù)操縱(此處特別鳴謝我研究生生涯階段的師兄給我講解了很久關(guān)于Web編程方面的知識,收益良多。希望大家利用相關(guān)時間,多去查詢資料和相關(guān)視頻進行學習);
(2)entity包:這里存放我們的實體類,跟單純學java里面建立類一模一樣,沒有區(qū)別;
(3)mapper包:SpringMVC中稱之為持久層也就是(DAO層(數(shù)據(jù)訪問對象)),這里可以直接對數(shù)據(jù)庫進行操作,一般與第五個包mapping包連用;
(4)service包:SpringMVC中稱之為業(yè)務邏輯層,所以這里存放的類都是處理相關(guān)的業(yè)務邏輯;
(5)mapping包:放在resources下面作為classpath,存放的mybatis文件,因為現(xiàn)在的SpringBoot集成性很強,把很多配置文件都可以放在一塊,哪怕是沒有太多的mybatis基礎(chǔ)的小伙伴也可以進行學習。之所以說mapper包與mapping包是一起連用,是因為它們形成映射關(guān)系,它們兩的結(jié)合使用來訪問我們的數(shù)據(jù)庫文件;
(6)application.yml:作為全局默認配置文件,適用于整個項目,要整合我們這么多的配置信息,這個配置文件肯定少不了(此處最好是使用yaml語言編寫配置文件,因為編寫相對而言簡單明朗一些);
(7)application-dev.yml:這個算是具體某個環(huán)境的配置文件,具體要結(jié)合我們的實際項目。因為項目本身不只是開發(fā)環(huán)境,還有測試、生產(chǎn)等一系列環(huán)境。當我們做開發(fā)是用開發(fā)的環(huán)境配置application-dev.yml,當我們做測試的時候用測試的環(huán)境配置application-test.yml,當我們做生產(chǎn)的時候用的是生產(chǎn)的環(huán)境配置application-pro.yml。目前我們暫時只說開發(fā)環(huán)境,所以就只用到了一個配置文件application-dev.yml。具體的某個環(huán)境配置信息在使用時會覆蓋applicaiton.yml的默認配置,所以,不用擔心默認配置中的語句與環(huán)境配置中的語句發(fā)生沖突。

(1)程序入口

每個java程序都有程序入口,DemoApplication本身在我們初始化SpringBoot時就已經(jīng)存在了,我們在這里不需要做過多的配置。

package com.example.demo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

●@SpringBootApplication注解:是用來表示這是一個springboot項目的啟動項類,目的是開啟自動配置(其實它是繼承于Configuration配置類,深解需要大家去剖析SpringBoot的原理)
●@MapperScan(“com.example.demo.mapper”)是為了掃描我們的mapper文件,進行有效訪問相關(guān)數(shù)據(jù)庫文件URL映射(這個注解的作用很大!)

(2)建立數(shù)據(jù)庫文件

●相應的sql創(chuàng)建表語句如下所示:

CREATE TABLE `water` (
  `id` int NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `salary` double(10,2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8_unicode_ci;

(3)建立User實體類

package com.example.demo.entity;

/**
 * @description:    實體類
 * @author: Fish_Vast
 * @Date: 2021/8/25
 * @version: 1.0
 */
public class User {
    private String name;
    private Integer id;
    private Double salary;

    public User() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

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

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", salary=" + salary +
                '}';
    }
}

●這里想必大家不會陌生,這是純Java基礎(chǔ)都能編寫出來的類,建立三個私有屬性,一個空參構(gòu)造器,相應的get、set方法,還重寫了一個toString()方法。這里值得注意的點是在聲明屬性時,最好是使用包裝類進行聲明。
●在Java中跟mybatis相關(guān)的讀取與錄入,為何盡量使用包裝類而不使用基本數(shù)據(jù)類型呢?
①在MySQL中沒有給字段賦值默認為null,當你從數(shù)據(jù)庫中查出來也是null,如果該字段在對應的Java代碼中是int類型,null不能對應int類型,因為int代表的是基本數(shù)據(jù)類型,只能是基本的數(shù)字。
②實體類的屬性可以給它賦值也可以不給它賦值,當你不給它賦值時,它擁有默認值,比如int的默認值就為0。但是主動為它設置值為0與它默認為0是兩個不同的概念。比如,一個班的成績:0代表某學生分數(shù)為0,而null代表這個學生該門考試沒有成績,這是兩個不同的概念。

(4)建立UserMapper接口

package com.example.demo.mapper;

import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper {
    //1.通過id查詢用戶信息
    User getUser(int id);
    //2.通過id刪除用戶信息
    int delete(int id);
    //3.更改用戶信息
    int update(User user);
    //4.插入用戶信息
    int save(User user);
    //5.查詢所有用戶信息
    List<User> selectAll();
}

●@Repository,注解它本身的作用便是標注數(shù)據(jù)訪問組件,作為DAO對象,它將 DAO 導入 IoC 容器,并使未經(jīng)檢查的異常有資格轉(zhuǎn)換為 Spring DataAccessException。通過這個注解能夠報出更多發(fā)現(xiàn)不了的錯誤,更有利于對項目的維護和開發(fā)。其實@Repository不在接口上進行注明,我們的程序照樣可以運行,因為在我們使用@MapperScan的時候,我們已經(jīng)將我們的接口交給框架中的代理類,所以即便是我們不寫,程序不會報錯,只是我們在Service層寫明接口的時候,IDEA會給出紅色的波浪線??梢赃@樣理解,標注@Repository是為了告訴編譯器我將接口注入到了IoC容器了,你不要報錯啦~
●相應地,寫出增刪查改和查詢?nèi)啃畔⒌奈鍌€方法。

(5)配置UserMapper.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.example.demo.mapper.UserMapper">
    <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
        <result column="id" jdbcType="INTEGER" property="id" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="salary" jdbcType="DOUBLE" property="salary" />
    </resultMap>
    <!--查詢用戶信息-->
    <select id="getUser" resultType="com.example.demo.entity.User">
        select * from water where id = #{id}
    </select>
    <!--刪除用戶信息-->
    <delete id="delete" parameterType="int">
        delete from water where id=#{id}
    </delete>
    <!--返回所有用戶信息-->
    <select id="selectAll"  resultType="com.example.demo.entity.User">
        select * from water
    </select>

    <!--增加用戶信息-->
    <insert id="save" parameterType="com.example.demo.entity.User" >
        insert into water
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="name != null" >
                name,
            </if>
            <if test="salary != null" >
                salary,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null" >
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="salary != null" >
                #{salary,jdbcType=DOUBLE},
            </if>
        </trim>
    </insert>

    <!--根據(jù)id更改用戶信息-->
    <update id="update" parameterType="com.example.demo.entity.User">
        update water
        <set >
            <if test="name != null" >
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="salary != null" >
                salary = #{salary,jdbcType=DOUBLE},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
</mapper>

●mapper namespace用于綁定mapper接口的,當你的namespace綁定接口后,你可以不用寫接口實現(xiàn)類,mybatis會通過該綁定自動幫你找到對應要執(zhí)行的SQL語句(通過mapper方法名進行綁定);
●resultMap 定義了一個id為BaseResultMap的標識,type代表使用哪種類作為我們所要映射的類;
●<select id="getUser" resultType="com.example.demo.entity.User">在這里中的id = “xxx” ,必須要和mapper接口方法名保持一致,如果不一致,程序會報相應的錯誤。

(6)建立UserService類

package com.example.demo.service;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:	實現(xiàn)類,對進行相關(guān)的業(yè)務邏輯
 * @author: Fish_Vast
 * @Date: 2021/8/25
 * @version: 1.0
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUser(int id){    
        return userMapper.getUser(id);
    }

    public int delete(int id){
        return userMapper.delete(id);
    }

    public int update(User user){
        return userMapper.update(user);
    }

    public int save(User user){
        return userMapper.save(user);
    }

    public List<User>  selectAll(){
        return userMapper.selectAll();
    }
}

●這里我特別說明一下,private UserMapper userMapper既可以當做是引用數(shù)據(jù)類型,也可以作為接口對象進行使用,這里我們當接口對象使用(初次接觸的時候肯定對這個會有些許疑問,很正常,因為我當時對于這個接口也糾結(jié)了很久哦);
●@Service表示我們在業(yè)務邏輯層進行操縱,屬于自動配置的環(huán)節(jié);
●相應的五個方法,通過對象得到相應返回值給UserMapper接口。

(7)建立UserController類

package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.xml.ws.Service;
import java.util.List;

/**
 * @description:	控制器,接收并響應相關(guān)信息
 * @author: Fish_Vast
 * @Date: 2021/8/25
 * @version: 1.0
 */
@RestController
@RequestMapping("/seven")
public class UserController {
    @Autowired
    private UserService userService;
    //通過id得到用戶信息
    @RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
    public String getUser(@PathVariable int id){
        return userService.getUser(id).toString();
    }
    //通過id刪除用戶信息
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(int id){
        int result = userService.delete(id);
        if(result >= 1){
            return "刪除成功!";
        }else{
            return "刪除失敗!";
        }
    }
    //更改用戶信息
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(User user){
        int result = userService.update(user);
        if(result >= 1){
            return "更新成功!";
        }else{
            return "更新失?。?;
        }
    }
    //插入用戶信息
    @RequestMapping(value = "/insert", method = RequestMethod.GET)
    public int insert(User user){
        return userService.save(user);
    }
    //查詢所有用戶的信息
    @RequestMapping(value = "/selectAll")
    @ResponseBody   //理解為:單獨作為響應體,這里不調(diào)用實體類的toString方法
    public List<User>  listUser(){
        return userService.selectAll();
    }
}

●@RestController注解:就表示我們在控制層模塊??刂茖邮亲鳛镾pringMVC最重要的一個環(huán)節(jié),進行前端請求的處理,轉(zhuǎn)發(fā),重定向,還包括調(diào)用Service方法;
●@RequestMapping注解:處理請求和控制器方法之間的映射關(guān)系;
●@ResponseBody注解:將返回的數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換為JSON格式響應到瀏覽器(這里說得比較籠統(tǒng),只是簡單滴給大家說明一下,水平還不夠,認識還不深,不到之處還請見諒?。?;
●更多的注解解釋,還需要大家多去學習一下SpringMVC和SpringBoot,這里面會詳細地介紹,在這里我只是做了很粗略的說明而已(本人也是正接觸不久,正在努力學習當中)。

(8)配置application.yml文件

spring:
  profiles:
    active: dev

●語句很簡單,指明我們要使用的開發(fā)環(huán)境配置文件

(9)配置application-dev.yml

#服務器端口配置
server:
  port: 8081

#數(shù)據(jù)庫配置
spring:
  datasource:
    username: 數(shù)據(jù)庫名稱
    password: 賬號密碼
    url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf-8&nullCatalogMeansCurrent=true&useSSL=true&&serverTimezone=Asia/Shanghai
    driver-class-name: com.mysql.cj.jdbc.Driver

#mybatis配置
mybatis:
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.example.demo.entity

#showSQL
logging:
  level:
    com.example.demo.entity: debug

●在開發(fā)配置文件當中,我們配置好我們的服務器端口號、數(shù)據(jù)庫的配置、mybatis的配置和如何展示我們的Sql;
●其中要注意的是,數(shù)據(jù)庫的配置中的username和password使用我們安裝MySQL數(shù)據(jù)庫時使用的賬號名稱和密碼,url中的3306/緊跟著我們的數(shù)據(jù)庫名稱,如果建立的數(shù)據(jù)庫名稱不一致,也需要進行修改。

(10)效果展示

通過以上9個步驟,我們從第(1)個步驟程序入口處點擊運行按鈕,在瀏覽器中輸入相應指令即可得到不同的展示信息:(到這一步,大概知道為啥要使用@MapperScan注解了吧,可以直接將掃描到的包文件交到代理類中,SpringBoot就是很人性化的框架?。?/p>

①查詢操作:http://localhost:8081/seven/getUser/1

②刪除操作:http://localhost:8081/seven/delete?id=14

③更改操作:http://localhost:8081/seven/update?id=1&name=小丸子&salary=12000

④插入操作:http://localhost:8081/seven/insert?id=15&name=浩子&salary=13000

⑤查詢?nèi)坑脩粜畔ⅲ篽ttp://localhost:8081/seven/selectAll

到此這篇關(guān)于Java之SpringBoot實現(xiàn)基本增刪改查(前后端分離版)的文章就介紹到這了,更多相關(guān)SpringBoot增刪改查內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論