1.데이터 및 구조 설계 [데이터 유효성 검증]

dasd412·2022년 1월 29일
0

포트폴리오

목록 보기
6/41

프로젝트에서 사용한 검증 방식은 구글 구아바 라이브러리다.

모델 레이어 내에서 엔티티 생성 또는 변경 시 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("작성자가 없습니다."));
    }
}
profile
아키텍쳐 설계와 테스트 코드에 관심이 많음.

0개의 댓글