프로젝트에서 사용한 검증 방식은 구글 구아바 라이브러리다.
모델 레이어 내에서 엔티티 생성 또는 변경 시 checkArgument()를 호출해서 유효한지 검사한다.
import static com.google.common.base.Preconditions.checkArgument;
@Entity
@Table(name = "DiabetesDiary", uniqueConstraints = @UniqueConstraint(columnNames = {"diary_id"}))
@IdClass(DiabetesDiaryId.class)
public class DiabetesDiary {
@Id
@Column(name = "diary_id", columnDefinition = "bigint default 0")
private Long diaryId;
@Id
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "writer_id")
private Writer writer;
@Column(name = "fpg")
private int fastingPlasmaGlucose;
private String remark;
private LocalDateTime writtenTime;
@OneToMany(mappedBy = "diary",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private final Set<Diet> dietList = new HashSet<>();
public DiabetesDiary() {
}
public DiabetesDiary(EntityId<DiabetesDiary, Long> diabetesDiaryEntityId, Writer writer, int fastingPlasmaGlucose, String remark, LocalDateTime writtenTime) {
checkArgument(fastingPlasmaGlucose > 0 && fastingPlasmaGlucose <= 1000, "fastingPlasmaGlucose must be between 1 and 1000");
checkArgument(remark.length() <= 500, "remark length should be lower than 501");
this.diaryId = diabetesDiaryEntityId.getId();
this.writer = writer;
this.fastingPlasmaGlucose = fastingPlasmaGlucose;
this.remark = remark;
this.writtenTime = writtenTime;
}
private void modifyFastingPlasmaGlucose(int fastingPlasmaGlucose) {
checkArgument(fastingPlasmaGlucose > 0 && fastingPlasmaGlucose <= 1000, "fastingPlasmaGlucose must be between 1 and 1000");
this.fastingPlasmaGlucose = fastingPlasmaGlucose;
}
private void modifyRemark(String remark) {
checkArgument(remark.length() <= 500, "remark length should be lower than 501");
this.remark = remark;
}
}
서비스 레이어에도 사용한다.
파라미터로 받는 id가 null이면 checkNotNull()에 의해서 예외가 던져진다.
@Service
public class FindDiaryService {
@Transactional(readOnly = true)
public Writer getWriterOfDiary(EntityId<DiabetesDiary, Long> diaryEntityId) {
checkNotNull(diaryEntityId, "diaryId must be provided");
return diaryRepository.findWriterOfDiary(diaryEntityId.getId()).orElseThrow(() -> new NoResultException("작성자가 없습니다."));
}
}