SpringBoot———实现增删改查操作

SpringBoot———实现增删改查操作



前言


提示:以下是本篇文章正文内容,下面案例可供参考

一、创建一个springboot项目工程

二、准备一个数据库表

create table dept(
    id int unsigned primary key auto_increment ***ment,
    name varchar(10) not null unique ***ment  
    create_time datetime not null ***ment  
    update_time datetime not null ***ment  '
)

2.配置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>
    <groupId>***.example</groupId>
    <artifactId>tlias-web-management</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tlias-web-management</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.6.13</spring-boot.version>
    </properties>
    <dependencies>

        <!--        web起步依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--        mybatis起步依赖-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <!--        mysql驱动包-->
        <dependency>
            <groupId>***.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--        Lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--        springboot单元测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-***piler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>${spring-boot.version}</version>
                <configuration>
                    <mainClass>***.example.tliaswebmanagement.TliasWebManagementApplication</mainClass>
                    <skip>true</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

3.在resources写application.propertiesl配置文件,连接数据库

# 应用服务 WEB 访问端口
server.port=8080

spring.datasource.driver-class-name=***.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC

#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=root

#配置mybatis的日志,指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#开启mybatis的驼峰命名自动映射开关。a_column ------>aColumn
mybatis.configuration.map-underscore-to-camel-case=true


三、创建一个Dept实体类

 package ***.example.tliaswebmanagement.***.itheima.pojo;
/**
 * @Author 小浩
 * @Date 2023/10/25 17:51
 * @PackageName:***.example.tliaswebmanagement.***.itheima.pojo
 * @ClassName: PageBean
 * @Description  实体类
 */
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDate;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept {

    private Integer id;  //ID
    private String name;  //部门名称
    private LocalDate createTime;  //创建时间
    private LocalDate updateTime;  // 修改时间
}

1、创建DeptController

package ***.example.tliaswebmanagement.***.itheima.controller;


import ***.example.tliaswebmanagement.***.itheima.pojo.Dept;
import ***.example.tliaswebmanagement.***.itheima.pojo.Result;
import ***.example.tliaswebmanagement.***.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门管理Controller
 */
@Slf4j  //lombok提供了日志
@RestController
@RequestMapping("/depts")
public class DeptController {

    @Autowired
    private DeptService deptService;
    /**
     * 查询部门数据
     *
     * @return
     */
    @GetMapping
    public Result list() {
        log.info("查询全部部门数据");
        //调用service查询部门数据
        List<Dept> list = deptService.list();
        return Result.su***ess(list);
    }

    /**
     * 通过id删除部门id
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("根据id删除部门:{}", id);
        //调用service删除部门
        deptService.delete(id);
        return Result.su***ess();
    }

    /**
     * 新增部门
     *
     * @param dept
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Dept dept) {
        log.info("新增部门:{}", dept);
        //调用service新增部门
        deptService.add(dept);
        return Result.su***ess();
    }

    /**
     * 修改部门
     *
     * @return
     */

    @PutMapping
    public Result update(Dept dept) {
        log.info("修改部门");
      //调用service修改部门
        deptService.update(dept);
        return Result.su***ess();
    }

}

2、创建DeptService接口


/**
 * @Author 小浩
 * @Date 2023/10/25 17:51
 * @PackageName:***.example.tliaswebmanagement.***.itheima.pojo
 * @ClassName: PageBean
 * @Description  实体类
 */
    /**
     * 查询全部部门数据
     * @return
     */
    List<Dept> list();


    /**
     * 删除部门
      * @return
     */
    void  delete(Integer id);


    /**
     * 新增部门
     * @param dept
     */
    void add(Dept dept);


    /**
     * 修改部门
     * @param dept
     */
    int  update(Dept dept);

3、创建一个 DeptServiceImpl实现类

package ***.example.tliaswebmanagement.***.itheima.service.impl;
/**
 * @Author 小浩
 * @Date 2023/10/25 17:51
 * @PackageName:***.example.tliaswebmanagement.***.itheima.pojo
 * @ClassName: PageBean
 * @Description  实体类
 */
import ***.example.tliaswebmanagement.***.itheima.mapper.DeptMapper;
import ***.example.tliaswebmanagement.***.itheima.pojo.Dept;
import ***.example.tliaswebmanagement.***.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class DeptServiceImpl  implements DeptService {

    @Autowired
    private DeptMapper deptMapper;


    /**
     * 查询全部部门
     * @return
     */
    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    /**
     * 根据id删除部门
     * @param id
     */
    @Override
    public void  delete(Integer id) {
        deptMapper.deleteById(id);
    }


    /**
     * 新增部门
     * @param dept
     */
    @Override
    public void add(Dept dept) {

        dept.setCreateTime(LocalDate.now());
        dept.setUpdateTime(LocalDate.now());
        deptMapper.insert(dept);

    }


    /**
     * 修改部门
     * @param dept
     */
    @Override
    public int update(Dept dept) {

       return  deptMapper.Update(dept);
    }
}

4、创建DeptMapper接口

package ***.example.tliaswebmanagement.***.itheima.mapper;

import ***.example.tliaswebmanagement.***.itheima.pojo.Dept;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @Author 小浩
 * @Date 2023/10/25 15:56
 * @PackageName:***.example.tliaswebmanagement.***.itheima.mapper
 * @ClassName: DeptMapper
 * @Description
 */

/**
 * 部门管理
 */
@Mapper
public interface DeptMapper {


    //查询全部部门
    @Select("select  * from  dept")
    List<Dept> list();

    /**
     * 根据id删除部门
     *
     * @param id
     */
    @Delete("delete from dept where id = #{id}")
    void deleteById(Integer id);


    /**
     * 新增部门
     * @param dept
     */
    @Insert("insert into  dept(name, create_time, update_time) values (#{name},#{createTime},#{updateTime})")
    void insert(Dept dept);


    /**
     * 修改部门信息
     * @param
     */
    @Update("update  dept set create_time = #{createTime}, update_time = #{updateTime}  where id = #{id}")
    int  Update(Dept dept);
}

最后在运行项目在postman测试

转载请说明出处内容投诉
CSS教程_站长资源网 » SpringBoot———实现增删改查操作

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买