SpringBoot 基本增删改查的业务逻辑实现

47 篇文章 0 订阅
26 篇文章 0 订阅

基本思路:EasyCode 根据students表生成第一版代码,然后补充基本逻辑

在这里插入图片描述

第1步:创建表然后插入数据

[Ref] SpringBoot 初次配置数据库 并 进行第一次业务查询

第2步:使用 EasyCode 生成Controller层,Service层,Repository层,Model模型代码

[Ref] IDEA+EasyCode实现代码生成(傻瓜式教程

在这里插入图片描述
Model

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private Integer height;
    private String gender;
    private Integer classId;
    private Boolean isDelete;
}

在这里插入图片描述
Repository

package com.zhangziwa.practisesvr.mapper;

import com.zhangziwa.practisesvr.model.Student;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * (Students)表数据库访问层
 *
 * @author makejava
 * @since 2024-01-16 12:22:58
 */
public interface StudentsMapper {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Student queryById(Integer id);

    /**
     * 查询指定行数据
     *
     * @param student 查询条件
     * @return 对象列表
     */
    List<Student> queryAllByLimit(Student student);

    /**
     * 统计总行数
     *
     * @param student 查询条件
     * @return 总行数
     */
    long count(Student student);

    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 影响行数
     */
    int insert(Student student);

    /**
     * 批量新增数据(MyBatis原生foreach方法)
     *
     * @param entities List<Students> 实例对象列表
     * @return 影响行数
     */
    int insertBatch(@Param("entities") List<Student> entities);

    /**
     * 批量新增或按主键更新数据(MyBatis原生foreach方法)
     *
     * @param entities List<Students> 实例对象列表
     * @return 影响行数
     * @throws org.springframework.jdbc.BadSqlGrammarException 入参是空List的时候会抛SQL语句错误的异常,请自行校验入参
     */
    int insertOrUpdateBatch(@Param("entities") List<Student> entities);

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 影响行数
     */
    int update(Student student);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 影响行数
     */
    int deleteById(Integer id);
}
<?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.zhangziwa.practisesvr.mapper.StudentsMapper">

    <resultMap type="com.zhangziwa.practisesvr.model.Student" id="StudentsMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
        <result property="height" column="height" jdbcType="NUMERIC"/>
        <result property="gender" column="gender" jdbcType="VARCHAR"/>
        <result property="classId" column="class_id" jdbcType="INTEGER"/>
        <result property="isDelete" column="is_delete" jdbcType="VARCHAR"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="StudentsMap">
        select id,
               username,
               password,
               age,
               height,
               gender,
               class_id,
               is_delete
        from students
        where id = #{id}
    </select>

    <!--查询指定行数据-->
    <select id="queryAllByLimit" resultMap="StudentsMap">
        select
        id, username, password, age, height, gender, class_id, is_delete
        from students
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="username != null and username != ''">
                and username = #{username}
            </if>
            <if test="password != null and password != ''">
                and password = #{password}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="height != null">
                and height = #{height}
            </if>
            <if test="gender != null and gender != ''">
                and gender = #{gender}
            </if>
            <if test="classId != null">
                and class_id = #{classId}
            </if>
            <if test="isDelete != null">
                and is_delete = #{isDelete}
            </if>
        </where>
    </select>

    <!--统计总行数-->
    <select id="count" resultType="java.lang.Long">
        select count(1)
        from students
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="username != null and username != ''">
                and username = #{username}
            </if>
            <if test="password != null and password != ''">
                and password = #{password}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="height != null">
                and height = #{height}
            </if>
            <if test="gender != null and gender != ''">
                and gender = #{gender}
            </if>
            <if test="classId != null">
                and class_id = #{classId}
            </if>
            <if test="isDelete != null">
                and is_delete = #{isDelete}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into students(username, password, age, height, gender, class_id, is_delete)
        values (#{username}, #{password}, #{age}, #{height}, #{gender}, #{classId}, #{isDelete})
    </insert>

    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into students(username, password, age, height, gender, class_id, is_delete)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.username}, #{entity.password}, #{entity.age}, #{entity.height}, #{entity.gender},
            #{entity.classId}, #{entity.isDelete})
        </foreach>
    </insert>

    <insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
        insert into students(username, password, age, height, gender, class_id, is_delete)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.username}, #{entity.password}, #{entity.age}, #{entity.height}, #{entity.gender},
            #{entity.classId}, #{entity.isDelete})
        </foreach>
        on duplicate key update
        username = values(username),
        password = values(password),
        age = values(age),
        height = values(height),
        gender = values(gender),
        class_id = values(class_id),
        is_delete = values(is_delete)
    </insert>

    <!--通过主键修改数据-->
    <update id="update">
        update students
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
            <if test="height != null">
                height = #{height},
            </if>
            <if test="gender != null and gender != ''">
                gender = #{gender},
            </if>
            <if test="classId != null">
                class_id = #{classId},
            </if>
            <if test="isDelete != null">
                is_delete = #{isDelete},
            </if>
        </set>
        where id = #{id}
    </update>

    <!--通过主键删除-->
    <delete id="deleteById">
        delete
        from students
        where id = #{id}
    </delete>

</mapper>

在这里插入图片描述
Service

package com.zhangziwa.practisesvr.service;

import com.zhangziwa.practisesvr.model.Student;

import java.util.List;

/**
 * (Students)表服务接口
 *
 * @author makejava
 * @since 2024-01-16 12:23:01
 */
public interface StudentService {

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    Student queryById(Integer id);

    /**
     * 分页查询
     *
     * @param student 筛选条件
     * @return 查询结果
     */
    List<Student> queryByPage(Student student, Integer pageNum, Integer pageSize);

    Long queryCount(Student student);

    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    Student insert(Student student);

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    Student update(Student student);

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    boolean deleteById(Integer id);
}
package com.zhangziwa.practisesvr.service.serviceImpl;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.zhangziwa.practisesvr.mapper.StudentsMapper;
import com.zhangziwa.practisesvr.model.Student;
import com.zhangziwa.practisesvr.service.StudentService;
import com.zhangziwa.practisesvr.utils.pagehelper.PageHeaderUtils;
import com.zhangziwa.practisesvr.utils.pagehelper.PageUtils;
import com.zhangziwa.practisesvr.utils.response.ResponseContext;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * (Students)表服务实现类
 *
 * @author makejava
 * @since 2024-01-16 12:23:02
 */
@Service("studentsService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentsMapper studentsMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Student queryById(Integer id) {
        return this.studentsMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param student    筛选条件
     * @return 查询结果
     */
    @Override
    public List<Student> queryByPage(Student student,Integer pageNum,Integer pageSize) {
        PageMethod.startPage(PageUtils.getPageNum(pageNum), PageUtils.getPageSize(pageSize), PageUtils.isQueryTotalCount());
        PageMethod.orderBy("id asc");

        List<Student> students = studentsMapper.queryAllByLimit(student);
        PageInfo<Student> studentPageInfo = PageInfo.of(students);

        PageHeaderUtils.setPageHeader(studentPageInfo);
        ResponseContext.setResponseCode(HttpStatus.OK);
        return students;
    }

    @Override
    public Long queryCount(Student student) {
        return this.studentsMapper.count(student);
    }

    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    public Student insert(Student student) {
        this.studentsMapper.insert(student);
        return student;
    }

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    public Student update(Student student) {
        this.studentsMapper.update(student);
        return this.queryById(student.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.studentsMapper.deleteById(id) > 0;
    }
}

在这里插入图片描述
Controller

package com.zhangziwa.practisesvr.controller;

import com.zhangziwa.practisesvr.model.Student;
import com.zhangziwa.practisesvr.service.StudentService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * (Students)表控制层
 *
 * @author makejava
 * @since 2024-01-16 12:22:55
 */
@RestController
@RequestMapping("students")
public class StudentController {
    /**
     * 服务对象
     */
    @Resource
    private StudentService studentService;

    /**
     * 分页查询
     *
     * @param student 筛选条件
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<List<Student>> queryByPage(Student student,
                                                     @RequestParam(value = "pageNum") Integer pageNum,
                                                     @RequestParam(value = "PageSize") Integer pageSize) {
        return ResponseEntity.ok(studentService.queryByPage(student, pageNum, pageSize));
    }

    @GetMapping("/count")
    public ResponseEntity<Long> queryCount(Student student) {
        return ResponseEntity.ok(studentService.queryCount(student));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Student> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(studentService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param student 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<Student> add(@RequestBody Student student) {
        return ResponseEntity.ok(studentService.insert(student));
    }

    /**
     * 编辑数据
     *
     * @param student 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<Student> edit(@RequestBody Student student) {
        return ResponseEntity.ok(studentService.update(student));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping("{id}")
    public ResponseEntity<String> deleteById(@PathVariable("id") Integer id) {
        boolean body = studentService.deleteById(id);
        if (body) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}

在这里插入图片描述

第3步:测试


在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


在这里插入图片描述
在这里插入图片描述

分页查询
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建独立的、基于Spring框架的Java应用程序的开源框架。它简化了Spring应用程序的开发过程,提供了一种快速、方便的方式来创建可独立运行的、生产级别的Spring应用程序。 在Spring Boot中,实现业务的增删改查通常需要以下几个步骤: 1. 定义实体类:首先,需要定义与业务相关的实体类,例如User、Product等。这些实体类通常使用注解来标识其属性和关系。 2. 创建数据访问层(DAO):在Spring Boot中,可以使用Spring Data JPA或者MyBatis等持久化框架来简化数据库操作。通过定义接口或者XML文件,可以实现对数据库的增删改查操作。 3. 创建业务逻辑层(Service):在业务逻辑层中,可以编写具体的业务逻辑代码,例如对数据进行校验、处理业务逻辑等。可以使用@Service注解将该类标识为Spring的Bean。 4. 创建控制器层(Controller):控制器层负责接收用户请求,并将请求转发给相应的业务逻辑层进行处理。可以使用@RestController注解将该类标识为Spring的Bean,并使用@RequestMapping注解定义请求路径。 5. 配置路由和参数绑定:在Spring Boot中,可以使用@RequestMapping注解来定义请求路径,并使用@RequestParam注解来绑定请求参数。 6. 返回结果:根据业务需求,可以将处理结果返回给用户。可以使用@ResponseBody注解将方法的返回值转换为JSON格式返回给客户端。 以上是Spring Boot实现业务增删改查的一般步骤。具体的实现方式会根据具体的业务需求和技术选型而有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值