第一次写后台,跟着大佬学习java后台开发。第一个任务就是写user接口,就跟着大佬以前的代码,磕磕碰碰开始写了。
Model层
@Data
@Document(collection = "user")
public class User {
@NotNull
@Id
@Field("user_id")
private String userId = UUID.randomUUID().toString();
@NotNull
@Field("username")
private String username;
@NotNull
@Field("password")
private String password;
@NotNull
private String nickname;
@NotNull
private String role;
private String token;
}复制代码
@Data:在类名上方加上了@Data注解, 为类提供读写属性, 此外还提供了equals()、
hashCode()、toString() 方法,可以简写代码。
@Document(collection = "xxx"):实体类将会映射到数据库中的名为xxx的collection。
@Field:用于POST请求,提交单个数据。(这个暂时还不是很懂?)
DAO层
@Repository
public interface UserRepository extends MongoRepository {
User findByUsername(String username);
}复制代码
@Repository:注解在持久层中,具有将数据库操作抛出的原生异常翻译转化为spring的持久层异常的功能。
Service层
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User save(User user) throws Exception {
user.setPassword(DigestUtils.sha256Hex(user.getPassword()));
return userRepository.save(user);
}
public User find(String userId) throws Exception {
return userRepository.findById(userId).orElse(null);
}
public Page findAll(Pageable pageable) throws Exception {
return userRepository.findAll(pageable);
}
public void delete(String userId) throws Exception {
User user = userRepository.findById(userId).orElse(null);
if (user == null) {
throw new IllegalArgumentException("No such user");
}
userRepository.delete(user);
}
}复制代码
@Service:业务逻辑层注解,这个注解只是标注该类处于业务逻辑层。
Controller层
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/user")
public Result saveUser(@RequestBody User user) throws Exception {
return new Result.Builder().setData(userService.save(user)).build();
}
@LoginRequired
@GetMapping("/user/{userId}")
public Result getUser(@PathVariable String userId, @CurrentUser User user) throws Exception {
return new Result.Builder().setData(userService.find(userId)).build();
}
@LoginRequired
@GetMapping("/user/{page}/{size}")
public Result getAll(@PathVariable Integer page, @PathVariable Integer size, @CurrentUser User user) throws Exception{
return new Result.Builder().setData(userService.findAll(PageRequest.of(page-1,size))).build();
}
@LoginRequired
@DeleteMapping("/user/{userId}")
public Result deleteUser(@PathVariable String userId, @CurrentUser User user) throws Exception {
userService.delete(userId);
return new Result.Builder().build();
}
}复制代码
@RestController:相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面。
看到大佬写的@Query还有findBy方法,还有一些注解,emmm打算这两天再研究一下。