当前位置:   article > 正文

Spring Boot 笔记 009 创建接口_更新用户基本信息

Spring Boot 笔记 009 创建接口_更新用户基本信息

1.1.1 给User实体类添加校验

  1. package com.geji.pojo;
  2. import com.fasterxml.jackson.annotation.JsonIgnore;
  3. import jakarta.validation.constraints.Email;
  4. import jakarta.validation.constraints.NotEmpty;
  5. import jakarta.validation.constraints.NotNull;
  6. import jakarta.validation.constraints.Pattern;
  7. import lombok.Data;
  8. import java.time.LocalDateTime;
  9. //lombok 在编译阶段,为实体类自动生成setter getter toString
  10. // pom文件中引入依赖 在实体类上添加注解
  11. @Data
  12. public class User {
  13. @NotNull
  14. private Integer id;//主键ID
  15. private String username;//用户名
  16. @JsonIgnore//让springmvc把当前对象转换成json字符串的时候,忽略password,最终的json字符串中就没有password这个属性了
  17. private String password;//密码
  18. @NotEmpty
  19. @Pattern(regexp = "^\\S{1,10}$")
  20. private String nickname;//昵称
  21. @NotEmpty
  22. @Email
  23. private String email;//邮箱
  24. private String userPic;//用户头像地址
  25. private LocalDateTime createTime;//创建时间
  26. private LocalDateTime updateTime;//更新时间
  27. }

1.1.1 UserController中添加update方法

  1. @PutMapping("/update")
  2. public Result update(@RequestBody @Validated User user) {
  3. userService.update(user);
  4. return Result.success();
  5. }

1.1.2 UserService中添加update接口

  1. package com.geji.service;
  2. import com.geji.pojo.User;
  3. public interface UserService {
  4. //根据用户名查找用户
  5. User findByUserName(String username);
  6. //根据用户名和密码注册
  7. void register(String username, String password);
  8. void update(User user);
  9. }

1.1.3 UserServiceImpl中添加update实现类

  1. @Override
  2. public void update(User user) {
  3. user.setUpdateTime(LocalDateTime.now());
  4. userMapper.update(user);
  5. }

1.1.4 UserMapper中添加update方法

  1. package com.geji.mapper;
  2. import com.geji.pojo.User;
  3. import org.apache.ibatis.annotations.Insert;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Select;
  6. import org.apache.ibatis.annotations.Update;
  7. @Mapper
  8. public interface UserMapper {
  9. //根据用户名查询用户
  10. @Select("select * from user where username=#{username}")
  11. User findByUserName(String username);
  12. //添加
  13. @Insert("insert into user(username,password,create_time,update_time)" +
  14. " values(#{username},#{password},now(),now())")
  15. void add(String username, String password);
  16. @Update("update user set nickname=#{nickname},email=#{email},update_time=#{updateTime} where id=#{id}")
  17. void update(User user);
  18. }

1.1.5 使用postman测试

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/86607
推荐阅读
相关标签
  

闽ICP备14008679号