• Springboot-案例 增删改查二


    准备

    前端程序、后端工程(web/mybatis/mysql/lombok)、数据库
    在这里插入图片描述

    开发规范

    GET:查询
    POST:新增
    PUT:修改
    DELETE:删除
    Result.java

    @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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    在这里插入图片描述

    示例1:查询 删除 增加部门
    @RestController
    @Slf4j
    //优化请求路径
    @RequestMapping("/depts")
    public class DeptController {
    
        @Autowired
        private DeptService deptService;
    
        @GetMapping
        public Result list(){
            log.info("查询部门信息");
            List<Dept> list = deptService.list();
            return Result.success(list);
        }
        @DeleteMapping("/{id}")
        public Result delete(@PathVariable Integer id){
            log.info("删除部门{}",id);
            deptService.delete(id);
            return Result.success();
        }
    
        /*
        * 页面请求参数 @RequestBody
        * */
        @PostMapping
        public Result add(@RequestBody Dept dept){
            log.info("新增部门{}",dept);
            deptService.add(dept);
            return Result.success();
        }
    }
    
    
    @Service
    public class DeptServiceImpl implements DeptService {
        @Autowired
        private DeptMapper deptMapper;
        @Override
        public List<Dept> list() {
            return deptMapper.list();
        }
    
        @Override
        public void delete(Integer id) {
            deptMapper.delete(id);
        }
    
        @Override
        public void add(Dept dept) {
            dept.setCreateTime(LocalDateTime.now());
            dept.setUpdateTime(LocalDateTime.now());
            deptMapper.add(dept);
        }
    }
    
    
    public interface DeptService {
        List<Dept> list();
    
        void delete(Integer id);
    
        void add(Dept dept);
    }
    
    @Mapper
    public interface DeptMapper {
        @Select("select * from dept")
        List<Dept> list();
    
        @Delete("delete from dept where id =#{id}")
        void delete(Integer id);
    
       @Insert("insert into dept(name,create_time,update_time) values (#{name},#{createTime},#{updateTime} )" )
        void add(Dept dept);
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    示例2:员工管理
    2.1分页查询(SQL语句查询)
    -- 分页查询
    -- 参数1:起始索引 = (页码-1)*每页需要展示的数据数
    -- 参数2 : 每页展示的数据数
    select * from emp limit 0,5;
    select * from emp limit 5,5;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    @Mapper
    public interface EmpMapper {
        @Select("select count(*) from emp")
        public Long count();
    
        /**
         * 分页查询
         * @param start
         * @param pageSize
         * @return
         */
        @Select("select * from emp limit #{start},#{pageSize}")
        public List<Emp> page(Integer start,Integer pageSize);
    }
    
    @Service
    public class EmpServiceImpl implements EmpService {
        @Autowired
        private EmpMapper empMapper;
        @Override
        public PageBean page(Integer page, Integer pageSize) {
            PageBean pageBean = new PageBean();
            pageBean.setTotal(empMapper.count());
            pageBean.setRows(empMapper.page((page-1)*pageSize,pageSize));
            return pageBean;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    分页插件 pageHelper
    		<dependency>
                <groupId>com.github.pagehelpergroupId>
                <artifactId>pagehelper-spring-boot-starterartifactId>
                <version>1.4.3version>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
     @Override
        public PageBean page(Integer page, Integer pageSize) {
            PageHelper.startPage(page,pageSize);
            List<Emp> list = empMapper.list();
            Page<Emp> p= (Page<Emp>) list;
            return new PageBean(p.getTotal(),p.getResult());
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    2.2 条件分页查询员工(动态SQL)
    select * from emp where username like concat('%','朱','%') and gender =1 and entrydate
        between '2023-10-01' and '2023-10-20' order by update_time desc ;
    
    • 1
    • 2
    @RestController
    @Slf4j
    public class EmpController {
        @Autowired
        private EmpService empService;
        //分页查询 分页参数 page没传递默认1  pageSize 默认10 日期参数 前面加 @DateTimeFormat(pattern = "yyyy-MM-dd")
        @GetMapping("/emps")
        public Result page(@RequestParam(defaultValue = "1") Integer page , @RequestParam(defaultValue = "5")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.page(page,pageSize,name,gender,begin,end );
            return Result.success(pageBean);
        }
        
    }
    
    @Service
    public class EmpServiceImpl implements EmpService {
        @Autowired
        private EmpMapper empMapper;
        @Override
        public PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
            PageHelper.startPage(page,pageSize);
            List<Emp> list = empMapper.list(name, gender, begin, end);
            Page<Emp> p= (Page<Emp>) list;
            return new PageBean(p.getTotal(),p.getResult());
        }
    
    }
    
    public interface EmpService {
        PageBean page(Integer page, Integer pageSize ,String name, Short gender, LocalDate begin, LocalDate end);
    }
    
    @Mapper
    public interface EmpMapper {
        public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
    }
    
    xml
        <select id="list" resultType="com.example.demo.pojo.Emp">
            select *
            from emp
            <where>
                <if test="name != null and name!='' ">
                    username 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>
                order by update_time desc
            </where>
    
        </select>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    POST 请求错误400
    [nio-8080-exec-3] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDate'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat java.time.LocalDate] for value [2023-10-1]; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2023-10-1]]
    
    • 1

    在这里插入图片描述
    注意:postman请求发送日期:严格要求yyyy-MM-dd 格式 2023-10-01

    2.3 新增员工
     @PostMapping
        public Result save(@RequestBody Emp emp){
            log.info("新增员工:{}",emp);
            empService.save(emp);
            return Result.success();
        }
    
    @Insert("insert into emp (username,password,gender,image,job,entrydate,dept_id,create_time,update_time) values (#{username},#{password},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
        void insert(Emp emp);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    文件上传
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>文件上传title>
    head>
    <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        姓名:<input type="text" name="username"><br>
        年龄:<input type="text" name="age"><br>
        头像:<input type="file" name="image"><br>
        <input type="submit" value="提交">
    form>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    本地存储

    @RestController
    @Slf4j
    public class UploadController {
        @PostMapping("/upload")
        public Result upload(String username, Integer age, MultipartFile image) throws IOException {
            log.info("文件上传 {},{},{}",username,age,image);
            String name = image.getOriginalFilename();//原始文件名
            String s = UUID.randomUUID().toString();
            image.transferTo(new File("E:\\"+s+name.substring(name.lastIndexOf("."))));
            return Result.success();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在Springboot 文件上传默认单个最大文件大小为1M。需要上传大文件,配置:

    #单个最大上传文件大小
    spring.servlet.multipart.max-file-size=10MB
    #单个请求最大上传大小(一次可上传多个)
    spring.servlet.multipart.max-request-size=100MB
    
    • 1
    • 2
    • 3
    • 4

    阿里云存储oss
    在这里插入图片描述
    依赖

    <dependency>
        <groupId>com.aliyun.ossgroupId>
        <artifactId>aliyun-sdk-ossartifactId>
        <version>3.15.1version>
    dependency>
    
    java 9.0以上
    <dependency>
        <groupId>javax.xml.bindgroupId>
        <artifactId>jaxb-apiartifactId>
        <version>2.3.1version>
    dependency>
    <dependency>
        <groupId>javax.activationgroupId>
        <artifactId>activationartifactId>
        <version>1.1.1version>
    dependency>
    
    <dependency>
        <groupId>org.glassfish.jaxbgroupId>
        <artifactId>jaxb-runtimeartifactId>
        <version>2.3.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    @Component
    public class AliOSSUtils {
        private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        private String accessKeyId = "";
        private String accessKeySecret = "";
        private String bucketName = "";
    
        public String upload(MultipartFile file) throws IOException {
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //避免文件覆盖
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
    
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            ossClient.putObject(bucketName,fileName,inputStream);
            String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
            ossClient.shutdown();
            return url;
    
        }
    }
     @Autowired
        private AliOSSUtils aliOSSUtils;
        @PostMapping("/upload")
        public Result upload( MultipartFile image) throws IOException {
            String url = aliOSSUtils.upload(image);
            return Result.success(url);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    2.4 修改员工

    查找

     //路径参数 id 用@PathVariable
        @GetMapping("/{id}")
        public Result getById(@PathVariable Integer id){
            Emp emp = empService.getById(id);
            return Result.success(emp);
        }
        
     	@Override
        public Emp getById(Integer id) {
            return empMapper.getById(id);
    
        }
        
        Emp getById(Integer id);
    
        @Select("select * from emp where id=#{id}")
        Emp getById(Integer id);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    修改

    	//根据id根新员工信息
        @PutMapping
        public Result updateById(@RequestBody Emp emp){
            empService.updateById(emp);
            return Result.success();
        }
     	@Override
        public void updateById(Emp emp) {
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.updateById(emp);
        }
        void updateById(Emp emp);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    void updateById(Emp emp);
    <update id="updateById">
            update emp
            <set>
                <if test="username != null and username !=''">
                    username = #{username},
                if>
                <if test="password != null and  password !=''">
                    password = #{password},
                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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    参数配置 properties

    在这里插入图片描述

    yml配置

    application.yml 或者application.yaml

    server:
      port: 9000
    
    • 1
    • 2

    ![在
    这里插入图片描述](https://img-blog.csdnimg.cn/5ae2da4c42e44a86be204497c3719ac8.png)

    yml语法

    在这里插入图片描述

    #定义对象 /Map集合
    user:
      name: 明太祖
      age: 22
    
    # 数组 List set
    hobby:
      - sing
      - jump
      - rap
      - basketball
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    spring properties文件替换yml
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=1234
    mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
    mybatis.configuration.map-underscore-to-camel-case=true
    
    spring.servlet.multipart.max-file-size=10MB
    spring.servlet.multipart.max-request-size=100MB
    aliyun.oss.endpoint=https://oss-cn-hangzhou.aliyuncs.com
    aliyun.oss.accessKeyId=
    aliyun.oss.accessKeySecret=
    aliyun.oss.bucketName=
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/mybatis?useSSL=false&characterEncoding=UTF-8
        username: root
        password: 1234
      servlet:
        multipart:
          max-file-size: 10MB
          max-request-size: 100MB
    #log-impl 日志 cam 驼峰命名
    mybatis:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
        map-underscore-to-camel-case: true
    
    #文件上传 multipa
    
    #自定义
    aliyun:
      oss:
        endpoint: https://oss-cn-hangzhou.aliyuncs.com
        accessKeyId: 
        accessKeySecret: 
        bucketName: 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    @ConfigurationProperties

    @value(“${ }”)太繁琐
    在这里插入图片描述
    使用示例:

    @Component
    public class AliOSSUtils {
        @Value("${aliyun.oss.endpoint}")
        private String endpoint;
        @Value("${aliyun.oss.accessKeyId}")
        private String accessKeyId ;
        @Value("${aliyun.oss.accessKeySecret}")
        private String accessKeySecret ;
        @Value("${aliyun.oss.bucketName}")
        private String bucketName ;
    
        public String upload(MultipartFile file) throws IOException {
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //避免文件覆盖
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
    
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            ossClient.putObject(bucketName,fileName,inputStream);
            String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
            ossClient.shutdown();
            return url;
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    @Component
    public class AliOSSUtils {
        @Autowired
        private AliOSSProperties aliOSSProperties;
        
        public String upload(MultipartFile file) throws IOException {
            String endpoint = aliOSSProperties.getEndpoint();
            String accessKeyId = aliOSSProperties.getAccessKeyId();
            String accessKeySecret = aliOSSProperties.getAccessKeySecret();
            String bucketName = aliOSSProperties.getBucketName();
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //避免文件覆盖
            String originalFilename = file.getOriginalFilename();
            String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
    
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
            ossClient.putObject(bucketName,fileName,inputStream);
            String url = endpoint.split("//")[0]+"//"+bucketName+"."+endpoint.split("//")[1]+"/"+fileName;
            ossClient.shutdown();
            return url;
    
        }
    }
    
    @Data
    @Component
    @ConfigurationProperties(prefix = "aliyun.oss")
    public class AliOSSProperties {
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
    
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    警告
    在这里插入图片描述
    引入依赖

    	<dependency>
               <groupId>org.springframework.bootgroupId>
               <artifactId>spring-boot-configuration-processorartifactId>
         dependency>
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    spring集成nacos简要笔记
    2023最新SSM计算机毕业设计选题大全(附源码+LW)之java医院疫情管理系统4f9a9
    【图像融合】基于matlab粒子群优化自适应多光谱图像融合【含Matlab源码 004期】
    hadoop 日志聚集功能配置 hadoop(十一)
    对接西部数据Western Digital EDI 系统
    Java内部类重点知识
    Spring编程常见错误50例-Spring AOP常见错误(上)
    学完高性能计算后的发展怎么样?
    js版微信测试号推送消息、生日、纪念日、网易云热评、舔狗日记【JavaScript版】保姆级教程 青龙面板做微信测试号推送生日、纪念日
    Java自定义注解
  • 原文地址:https://blog.csdn.net/qq_44761778/article/details/133876261