{
"username":"sun",
"password":"123",
"nickname":"孙悟空"
}
UserService @Service public class UserService { @Autowired private UserMapper userMapper; public int save(User user){ if (user.getId()==null) { return userMapper.insert(user); }else { return userMapper.update(user); } } }
UserController
@RestController @RequestMapping("/user") public class UserController { @Autowired private UserMapper userMapper; @Autowired private UserService userService; @GetMapping public List<User> index() { List<User> all=userMapper.findAll(); return all; } @PostMapping //@RequestBody User 将前台的jason对象转为java对象 public Integer save(@RequestBody User user) { //新增或者更新都在这个里面 return userService.save(user); }
DeleteMapping("/{id}") public Integer delete(@PathVariable Integer id) { //新增或者更新都在这个里面 return userMapper.deleteById(id); }
}
UserMapper
@Mapper public interface UserMapper { //这个select是mybatis里面提供的 @Select("select * from sys_user") List<User> findAll(); @Insert("INSERT INTO sys_user(username,password,nickname,email,phone,address)" + " VALUES(#{username},#{password},#{nickname},#{email},#{phone},#{address})") int insert(User user); int update(User user); }
@Delete("delete from sys_user where id = #{id}") Integer deleteById(@Param("id") Integer id);
User.xml 的配置文件 (改update)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.yinming.sprintboot.mapper.UserMapper"> <update id="update"> update sys_user <set> <if test="username!=null"> username=#{username}, </if> <!-- <if test="password!=null">--> <!-- password=#{password}--> <!-- </if>--> <if test="nickname!=null"> nickname=#{nickname}, </if> <if test="email!=null"> email=#{email}, </if> <if test="phone!=null"> phone=#{phone}, </if> <if test="address!=null"> address=#{address} </if> </set> <where> id=#{id} </where> </update> </mapper>
Invalid bound statement (not found): com.yinming.sprintboot.mapper.UserMapper.update
注意:报错是要添加Sprintboot 框架必须 user.xml做什么的
需要在配置文件 中添加配置
application.yml
mybatis: mapper-locations: classpath:mapper/*.xml #扫描所有mybatis所有xml文件
postman delete 测试