
update메소드를 만들 때는 다음과 같은 과정을 거친다.DB에서 불러온다.JPA에서는 set으로 자동 update가 된다.)보통 데이터를 조회하기 위한 유일값은 id를 사용하지만, 실무에서는 그렇지 않은 경우도 꽤 있다.
최근 개발하고 있는 Template Admin project에서는 Template의 고유 코드 값으로 조회한다.
그런데 문제는, 이 코드값도 update메소드에서 변경이 가능하도록 만들어야 한다.
그렇기에, 보통 update메소드와 달리 몇가지 체크할 로직이 있었다.
JPA에서 보통 entity를 만들 때, id값에 어노테이션으로 @GeneratedValue를 주어서 중복되지 않도록 한다.
하지만 이 경우, 코드값을 수정할 때, 수정된 코드값이 이미 db에 있는 값인지 중복 체크를 해주어야한다.
하지만, 만약에 코드값을 변경하지 않는다면, 수정하기위해 불러온 entity의 코드와, 수정할 request dto의 코드 값이 같아서 중복 체크에 걸리게 된다.
그렇기에, 고려해야할 것은 첫째로 중복체크 로직과 둘째로 코드를 변경하지 않고 다른 것을 변경할 경우 두가지를 고려하여 로직을 짜줘야한다.
@Query("select count(*) from NotificationTemplate n where n.templateCode = :code") int checkDuplicateCode(@Param("code") String code);
중복체크하는 쿼리다. JPQL을 사용하여 쿼리를 만들어줬다.
JPQL에서는 DB 테이블이 아닌, Entity객체에서 조회한다.
public TemplateDto updateTemplate(String templateCode, TemplateDto templateDto) { int check = templateRepository.checkDuplicateCode(templateDto.getTemplate_code()); NotificationTemplate notificationTemplate = findTemplate(templateCode); if (!notificationTemplate.getTemplateCode().equals(templateDto.getTemplate_code())) { if (check > 0) { throw new DuplicationCodeException(); } } notificationTemplate.setSubject(templateDto.getSubject()); notificationTemplate.setContent(templateDto.getContent()); notificationTemplate.setTemplateCode(templateDto.getTemplate_code()); notificationTemplate.setEnabled(templateDto.getEnabled()); return new TemplateDto(notificationTemplate);
update 메소드 로직이다.
첫째로, templateCode로 entity를 찾는다.
request dto와 entity의 code를 비교하여 같다면 그대로 수정해주면된다.
같지 않은 경우, request dto의 코드값을 db에서 비교해준다. (checkDuplicateCode메소드를 사용)
실무에서는 항상 id값을 통해 entity를 조회하지는 않는다.
조회하는 여러가지 경우가있고, client쪽에서 요구하는대로 로직을 만들어야하기 때문이다.
이럴 경우 중복체크와, 중복체크시 유의해야 할점을 놓치지 말자.
그럼 이만 ! ✋