SpringBoot 基本的一些类和接口的定义及其作用
ResultVO
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
| import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import java.io.Serializable; @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class ResultVO<T> implements Serializable {
private String code;
private String msg;
private T result;
public static <T> ResultVO<T> buildSuccess(T result) { return new ResultVO<T>("000", null, result); }
public static <T> ResultVO<T> buildFailure(String msg) { return new ResultVO<T>("400", msg, null); } }
|
Exception
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class BlogException extends RuntimeException { public BlogException(String message) { super(message); } public static BlogException tokenNotFound() { return new BlogException("Token 未找到"); } }
throw BlogException.phoneNotExist();
|
VO(与前端交互)
注解
1 2 3
| @Getter @Setter @NoArgsConstructor
|
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
| @NotNull(message = "name required")
@Length(min = 5, max = 200, message = "name should be between 5 to 200 characters long")
|
Controller
1 2 3 4 5 6 7 8 9
| @RestController @RequestMapping("/user") public class UserController { @Autowired UserService userService; @PostMapping("/register") public ResultVO<Boolean> registerUser(@Validated @RequestBody UserVO userVO) { return ResultVO.buildSuccess(userService.registerUser(userVO), "注册成功"); } }
|
注解
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Validated
@RequestBody
@RequestParam
|
PO(与数据库连接)
注解
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
| @Entity
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Id
@Column(name = "id")
@Basic
@ManyToOne
@ManyToMany:
@Lob:
public enum RoleEnum { ADMIN, USER } @Enumerated @Basic @Column(name = "role") @Enumerated(EnumType.STRING) private RoleEnum role;
|
Enum
1 2 3 4 5
| public enum RoleEnum { ADMIN, USER }
|
Repository
与数据库进行交互的接口,提供增删改查的方法
1 2 3 4 5 6 7 8 9 10 11
| package com.wcx.blog.BlogBackend.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.wcx.blog.BlogBackend.po.User;
public interface UserRepository extends JpaRepository<User, Integer> {
User findByPhone(String phone); }
|
自动生成 id
1 2 3
|
UserRepository.save(User);
|
如何使用 Repository 进行查找
1 2 3
| Tag tag = tagRepository.findById(Long.valueOf(id)).orElse(null);
|