Springboot 增删改查(简单版)

发布时间:2023-05-06 09:00

User.java:

package com.edward.helloworld.entity;

import lombok.Data;


@Data
public class User {
    private int id;
    private String name;
    private int age;
    private  int salary;
}

UserMapper.java:

package com.edward.helloworld.mapper;

import com.edward.helloworld.entity.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface UserMapper {

    // 查
    @Select(\"select * from user\")
    List findAll();

    // 增
    @Update(\"INSERT INTO `user` (`name`, `age`, `salary`) VALUES (#{name},#{age},#{salary});\")
    @Transactional
    void save(User user);

    // 改
    @Update(\"update user set name=#{name}, age=#{age}, salary=#{salary} where id=#{id};\")
    @Transactional
    void updateById(User user);

    // 删
    @Update(\"delete from user where id=#{id}\")
    @Transactional
    void deleteById(int id);
}

UserController.java:

package com.edward.helloworld.controller;


import com.edward.helloworld.entity.User;
import com.edward.helloworld.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(\"/user\")
public class UserController {

    // 引入接口
    @Resource
    UserMapper userMapper;    

    @GetMapping
    public String getUser() {
        return \"user\";
    }

    @GetMapping(\"/all\")
    public List getAllUser () {
        return userMapper.findAll();
    }

    @PostMapping(\"/add\")
    public String addUser(@RequestBody User user) {
        userMapper.save(user);
        return \"add success\";
    }

    @PutMapping(\"/update\") // 或 @PostMapping(\"/update\")
    public String updateUser(@RequestBody User user) {
        userMapper.updateById(user);
        return \"update success\";
    }

    @DeleteMapping(\"/delete/{id}\") // 或 @GetMapping(\"/delete/{id}\")
    public String deleteUser(@PathVariable(\"id\") int id) {
        userMapper.deleteById(id);
        return \"delete success\";
    }
}

修改前的数据表:

\"Springboot

Postman 调试:

\"Springboot

\"Springboot

\"Springboot

\"Springboot

修改后的数据表:

\"Springboot

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号