springBoot-web 學習案例

tomato和potato發表於2024-06-24

環境的準備

  • 準備資料庫表

  • 建立springboot工程,引入對應的起步依賴(web、mybatis、mysql驅動、lombok)

    • 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
          <modelVersion>4.0.0</modelVersion>
          <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>3.2.5</version>
              <relativePath/> <!-- lookup parent from repository -->
          </parent>
          <groupId>com.tomato</groupId>
          <artifactId>springboot-test</artifactId>
          <version>0.0.1-SNAPSHOT</version>
          <name>springboot-test</name>
          <description>springboot-test</description>
          <properties>
              <java.version>22</java.version>
          </properties>
          <dependencies>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
              <dependency>
                  <groupId>org.mybatis.spring.boot</groupId>
                  <artifactId>mybatis-spring-boot-starter</artifactId>
                  <version>3.0.3</version>
              </dependency>
      
              <dependency>
                  <groupId>com.mysql</groupId>
                  <artifactId>mysql-connector-j</artifactId>
                  <scope>runtime</scope>
              </dependency>
              <dependency>
                  <groupId>org.projectlombok</groupId>
                  <artifactId>lombok</artifactId>
                  <optional>true</optional>
              </dependency>
              <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-test</artifactId>
                  <scope>test</scope>
              </dependency>
              <dependency>
                  <groupId>org.mybatis.spring.boot</groupId>
                  <artifactId>mybatis-spring-boot-starter-test</artifactId>
                  <version>3.0.3</version>
                  <scope>test</scope>
              </dependency>
              <dependency>
                  <groupId>org.slf4j</groupId>
                  <artifactId>slf4j-api</artifactId>
                  <version>2.0.12</version>
              </dependency>
              <dependency>
                  <groupId>com.github.pagehelper</groupId>
                  <artifactId>pagehelper-spring-boot-starter</artifactId>
                  <version>1.4.6</version>
              </dependency>
      <!--        阿里雲OSS-->
              <dependency>
                  <groupId>com.aliyun.oss</groupId>
                  <artifactId>aliyun-sdk-oss</artifactId>
                  <version>3.15.1</version>
              </dependency>
              <dependency>
                  <groupId>javax.xml.bind</groupId>
                  <artifactId>jaxb-api</artifactId>
                  <version>2.3.1</version>
              </dependency>
              <dependency>
                  <groupId>javax.activation</groupId>
                  <artifactId>activation</artifactId>
                  <version>1.1.1</version>
              </dependency>
              <!-- no more than 2.3.3-->
              <dependency>
                  <groupId>org.glassfish.jaxb</groupId>
                  <artifactId>jaxb-runtime</artifactId>
                  <version>2.3.3</version>
              </dependency>
          </dependencies>
      
          <build>
              <plugins>
                  <plugin>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-maven-plugin</artifactId>
                      <configuration>
                          <excludes>
                              <exclude>
                                  <groupId>org.projectlombok</groupId>
                                  <artifactId>lombok</artifactId>
                              </exclude>
                          </excludes>
                      </configuration>
                  </plugin>
              </plugins>
          </build>
      
      </project>
      
  • 配置檔案application.yml中引入mybatis的配置資訊,準備對應的實體類

    • application.yml

      #資料庫配置
      spring:
        datasource:
          url: jdbc:mysql://localhost:3306/tlias
          username: root
          password: 123456
        #配置上傳群檔案大小為100MB
        servlet:
          multipart:
            max-request-size: 100MB
      #配置駝峰命名
      mybatis:
        configuration:
          log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
          map-underscore-to-camel-case: true
      #配置上傳檔案上限大小為10MB
      logging:
        logback:
          rollingpolicy:
            max-file-size: 10MB
      #配置阿里雲oss服務地址以及AccessKeyId金鑰
      aliyun:
        oss:
          endpiont: https://oss-cn-hangzhou.aliyuncs.com
          accessKeyId: LTAI5t5peYCJUpTZAQj3yVyh
          accessKeySecret: VWCmSmuI0iIqSxECrPrncSFrV4sPfR
          bucketName: web-tilas-toamto
      
  • 準備對應的Mapper、Service(介面、實現類)、Controller,pojo實體類等基礎結構

    • Controller

      • DeptController

        @RestController
        public class DeptController {
        }
        
      • EmpController

        @RestController
        public class EmpController {
        }
        
    • Mapper

      • DeptMapper

        @Mapper
        public interface DeptMapper {
        }
        
      • EmpMapper

        @Mapper
        public interface EmpMapper {
        }
        
    • Service

      • Service實現類

        • DeptServiceImpl

          @Service
          public class DeptServiceImpl implements DeptService {
          }
          
        • EmpServiceImpl

          @Service
          public class EmpServiceImpl implements DeptService {
          }
          
      • Service介面類

        • DeptService

          @Service
          public class DeptService {
          }
          
        • EmpService

          @Service
          public class DeptService {
          }
          
    • pojo

      • Dept

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Dept {
            private Integer id; //ID
            private String name; //部門名稱
            private LocalDateTime createTime; //建立時間
            private LocalDateTime updateTime; //修改時間
        }
        
      • Emp

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Emp {
            private Integer id; //ID
            private String username; //使用者名稱
            private String password; //密碼
            private String name; //姓名
            private Short gender; //性別 , 1 男, 2 女
            private String image; //影像url
            private Short job; //職位 , 1 班主任 , 2 講師 , 3 學工主管 , 4 教研主管 , 5 諮詢師
            private LocalDate entrydate; //入職日期
            private Integer deptId; //部門ID
            private LocalDateTime createTime; //建立時間
            private LocalDateTime updateTime; //修改時間
        }
        
      • Result

        @Data
        @NoArgsConstructor
        @AllArgsConstructor
        public class Result {
            private Integer code;//響應碼,1 代表成功; 0 代表失敗
            private String msg;  //響應資訊 描述字串
            private Object data; //返回的資料
        
            //增刪改 成功響應
            public static Result success(){
                return new Result(1,"success",null);
            }
            //查詢 成功響應
            public static Result success(Object data){
                return new Result(1,"success",data);
            }
            //失敗響應
            public static Result error(String msg){
                return new Result(0,msg,null);
            }
        }
        

部門功能實現

部門管理

部門列表查詢

DeptController

import com.tomato.Service.DeptService;
import com.tomato.pojo.Dept;
import com.tomato.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author Tomato
 */
@RestController
@RequestMapping("/depts")
public class DeptController {
    //
    @Autowired
    private DeptService deptService;

    /**
     * 部門查詢
     */
    @GetMapping
    public Result select(){
        List<Dept> deptList=deptService.select();
        return Result.success(deptList);
    }
}

DeptService

package com.tomato.Service;

import com.tomato.pojo.Dept;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public interface DeptService {
    /**
     * 部門查詢
     */
    List<Dept> select();
}

DeptServiceImpl

package com.tomato.Service.impl;

import com.tomato.Mapper.DeptMapper;
import com.tomato.Service.DeptService;
import com.tomato.pojo.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Tomato
 */
@Service
public class DeptServiceImpl implements DeptService {
    //
    @Autowired
    private DeptMapper deptMapper;
    /**
     * 部門查詢
     */
    @Override
    public List<Dept> select() {
        return deptMapper.select();
    }
}

DeptMapper

package com.tomato.Mapper;

import com.tomato.pojo.Dept;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface DeptMapper {
    /**
     * 部門查詢
     */
    List<Dept> select();
}

DeptMapper.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.tomato.Mapper.DeptMapper">
<!--    查詢部門資訊-->
    <select id="select" resultType="com.tomato.pojo.Dept">
        select * from dept
    </select>
</mapper>

刪除部門

DeptController

    /**
     * 刪除部門
     */
    @DeleteMapping("/{id}")
    public Result delect(@PathVariable Integer id){
        deptService.delect(id);
        return Result.success();
    }

DeptService

    /**
     * 刪除部門
     */
    void delect(Integer id);

DeptServiceImpl

    /**
     * 刪除部門
     */
    @Override
    public void delect(Integer id) {
        deptMapper.delect(id);
    }

DeptMapper

    /**
     * 刪除部門
     */
    void delect(Integer id);

DeptMapper.xml

<!--    刪除部門-->
    <delete id="delect">
        delete from dept where id=#{id}
    </delete>

新增部門

DeptController

    /**
     * 新增部門
     */
    @PostMapping
    public Result adds(@RequestBody Dept dept){
        deptService.adds(dept);
        return Result.success();
    }

DeptService

    /**
     * 新增部門
     */
    void adds(Dept dept);

DeptServiceImpl

    /**
     * 新增部門
     */
    @Override
    public void adds(Dept dept) {
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.adds(dept);
    }

DeptMapper

    /**
     * 新增部門
     */
    void adds(Dept dept);
}

DeptMapper.xml

<!--    新增部門-->
    <insert id="adds">
        insert into dept (name,create_time,update_time) values (#{name},#{createTime},#{updateTime})
    </insert>

根據ID查詢部門

DeptController

因為要查詢的是部門資料,所以要一定記住需要返回的是dept這個物件

    /**
     * 根據id查詢部門
     */
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
       Dept deptList= deptService.selectById(id);
        return Result.success(deptList);
    }

DeptService

    /**
     * 根據id查詢部門
     */
    Dept selectById(Integer id);

DeptServiceImpl

    /**
     * 根據id查詢部門
     */
    @Override
    public Dept selectById(Integer id) {
        Dept dept=deptMapper.selectById(id);
        return dept;
    }

DeptMapper

    /**
     * 根據id查詢部門
     */
    Dept selectById(Integer id);

DeptMapper.xml

    <!--    根據id查詢部門-->
    <select id="selectById" resultType="com.tomato.pojo.Dept">
        select * from dept where id=#{id}
    </select>

修改部門

DeptController

    /**
     * 修改部門
     */
    @PutMapping
    public Result update(@RequestBody Dept dept){
        deptService.update(dept);
        return Result.success();
    }

DeptService

    /**
     * 修改部門
     */
    void update(Dept dept);

DeptServiceImpl

    /**
     * 修改部門
     */
    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);

DeptMapper

    /**
     * 修改部門
     */
    void update(Dept dept);

DeptMapper.xml

<!--    修改部門-->
    <update id="update">
        update dept
        <set>
            <if test="name != null and name != ''">
                name= #{name},
            </if>
            <if test="createTime != null">
                create_time=#{createTime},
            </if>
            <if test="updateTime != null">
                update_time=#{updateTime}
            </if>
        </set>
        where id = #{id}
    </update>

員工管理

員工列表查詢

EmpController

package com.tomato.Controller;

import com.tomato.Service.EmpService;
import com.tomato.pojo.PageBean;
import com.tomato.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

/**
 * @author Tomato
 */
@Slf4j
@RequestMapping("/emps")
@RestController
public class EmpController {
    @Autowired
    private EmpService empService;

    /**
     * 分頁條件查詢員工資訊
     */
    @GetMapping
    private Result select(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize,
                          String name, Short gender,
                          @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                          @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end) {
        log.info("分頁條件查詢員工資訊:{},{},{},{},{},{}", page, pageSize, name, gender, begin, end);
        PageBean pageBean = empService.select(page, pageSize, name, gender, begin, end);
        return Result.success(pageBean);
    }
}

EmpService

package com.tomato.Service;

import com.tomato.pojo.PageBean;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public interface EmpService {
    /**
     * 分頁條件查詢員工資訊
     */
    PageBean select(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end);
}

EmpServiceImpl

package com.tomato.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tomato.Mapper.EmpMapper;
import com.tomato.Service.EmpService;
import com.tomato.pojo.Emp;
import com.tomato.pojo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * @author Tomato
 */
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    /**
     * 分頁條件查詢員工資訊
     */
    @Override
    public PageBean select(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
        //設定分頁引數
        PageHelper.startPage(page, pageSize);
        //執行查詢
        List<Emp> emplist = empMapper.select(name, gender, begin, end);
        Page<Emp> p = (Page<Emp>) emplist
        //封裝bean物件
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }
}

EmpMapper

package com.tomato.Mapper;

import com.tomato.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {
    /**
     * 分頁條件查詢員工資訊
     */
    List<Emp> select(String name, Short gender, LocalDate begin, LocalDate end);
}

EmpMapper.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.tomato.Mapper.EmpMapper">
<!--    條件分頁查詢員工資訊-->
    <select id="select" resultType="com.tomato.pojo.Emp">
        select *
        from emp
        <where>
            <if test="name != null and name!= '' ">
                name like concat('%', #{name}, '%')
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="begin != null and end != null  ">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>
</mapper>

刪除員工

EmpController

    /**
     * 批次刪除員工
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable List<Integer> ids){
        empService.delete(ids);
        return Result.success();
    }

EmpService

    /**
     * 批次刪除員工
     */
    void delete(List<Integer> ids);

EmpServiceImpl

    /**
     * 批次刪除員工
     */
    @Override
    public void delete(List<Integer> ids) {
        empMapper.delete(ids);
    }

EmpMapper

    /**
     * 批次刪除員工
     */
    void delete(List<Integer> ids);

EmpMapper.xml

主要是遍歷foreach的程式碼部分

    <!--     批次刪除員工
        collection:遍歷的集合
        item:遍歷出來的元素
        separator:分割符
        open:遍歷開始前拼接的sql片段
        close:遍歷結束後拼接的sql片段
     -->
    <delete id="delete">
        delete
        from emp
        where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

新增員工

EmpController

    /**
     * 新增員工
     */
    @PostMapping
    public Result add(@RequestBody Emp emp){
        empService.add(emp);
        return Result.success();
    }

EmpService

    /**
     * 新增員工
     */
    void add(Emp emp);

EmpServiceImpl

    /**
     * 新增員工
     */
    @Override
    public void add(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        emp.setPassword("123456");
        empMapper.add(emp);
    }

EmpMapper

    /**
     * 新增員工
     */
    void add(Emp emp);	

EmpMapper.xml

<!--    新增員工-->
    <insert id="add">
        insert into emp
        (username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time)
        values ( #{username}, #{password}, #{name}, #{gender}, #{image}
               , #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})
    </insert>

修改員工

EmpController

    /**
     * 修改員工
     */
    @PutMapping
    public Result update(@RequestBody Emp emp){
        empService.update(emp);
        return Result.success();
    }

EmpService

    /**
     * 修改員工
     */
    void update(Emp emp);

EmpServiceImpl

    /**
     * 修改員工
     */
    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);
    }

EmpMapper

    /**
     * 修改員工
     */
    void update(Emp emp);

EmpMapper.xml

<!--    修改員工資訊-->
    <update id="update">
        update emp
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="gender != null">
                gender = #{gender},
            </if>
            <if test="image != null and image != ''">
                image = #{image},
            </if>
            <if test="job != null">
                job = #{job},
            </if>
            <if test="entrydate != null">
                entrydate = #{entrydate},
            </if>
            <if test="deptId != null">
                dept_id = #{deptId},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime}
            </if>
        </set>
       where id = #{id}
    </update>

相關文章