Hiển thị thông báo xác thực
Bạn đã thiết lập các annotation như một lớp kiểm soát chất lượng cho dữ liệu doanh số game. Bây giờ hãy chạy xác thực trên dữ liệu có lỗi để xem các thông báo được in ra. Dữ liệu lỗi bị thiếu platform, có year trước 1960, và sales âm, những điều này vi phạm các ràng buộc được chỉ định trong annotation. Hãy xác thực dữ liệu doanh số game và in ra mọi thông báo vi phạm.
Các package jakarta đã được nhập sẵn cho bạn.
Bài tập này là một phần của khóa học
Làm sạch dữ liệu bằng Java
Hướng dẫn bài tập
- In thông báo vi phạm khi dữ liệu vi phạm một ràng buộc.
- Xác thực bản ghi bán game bằng cách áp dụng
validator.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
public class VideoGameSale {
@NotNull(message = "Name cannot be empty")
private String name;
@NotNull(message = "Platform cannot be empty")
private String platform;
@Min(value = 1960, message = "Year must be greater than 1960")
private Integer year;
@Min(value = 0, message = "Sales amount must be positive")
private Double sales;
public VideoGameSale(String name, String platform, Integer year, Double sales) {
this.name = name;
this.platform = platform;
this.year = year;
this.sales = sales;
}
public static void main(String[] args) {
VideoGameSale sale = new VideoGameSale(
"Super Mario Bros.", null, 1950,
-29.08);
Set> violations =
SalesValidator.validateSale(sale);
// Print the violation message
violations.forEach(violation ->
System.out.println(____.____()));
if (!violations.isEmpty()) throw new ConstraintViolationException(violations);
}
}
class SalesValidator {
private static final ValidatorFactory factory =
Validation.buildDefaultValidatorFactory();
private static final Validator validator = factory.getValidator();
public static Set> validateSale(VideoGameSale sale) {
// Validate the video game sale
return ____.____(sale);
}
}