发布时间: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\";
}
}
修改前的数据表:
Postman 调试:
修改后的数据表: