Spring Data DTO
2024. 12. 1. 16:33ㆍSpring Boot
DTO를 왜 쓸까?
1. 불필요한 데이터
기본적으로 Entitiy는 DB의 테이블과 매칭되어 있기 때문에 레코드의 모든 컬럼이 들어있다.
따라서 그냥 Entity를 넘겨주면 불필요한 데이터도 함께 제공하게 된다.
이는 보안뿐만 아니라 성능 하락과도 이어진다.
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class board_dto {
private Long id;
private String title;
private String writer;
}
@Query("select new com.example.mvc.postgreSQL.dto.board_dto(data.id, data.title, data.writer) from postgre_data data where :title is null or data.title Like %:title%")
@SuppressWarnings("null")
Page<board_dto> findAllByTitle(Pageable pageable, @Param("title") String title);
게시판의 글 목록에는 글의 내용은 필요 없다.
따라서 글의 data를 포함하지 않는 DTO를 만들어서 필요한 컬럼만 조회해서 사용하면 성능면에서 좋다
2. 데이터 변경 문제
Entity는 주로 영속화를 영속성 컨텍스트로 관리된다.
따라서 Entity를 그냥 사용하면 의도치 않은 데이터 변경이 일어 날수 있다
@Transactional
@CacheEvict(value = "board", key="#id", cacheManager = "contentCacheManager")
public data_dto update_data(Long id, data_dto data, String writer) {
postgre_data update = repo.findById(id).get();
if(update.getWriter() != null) {
if (!update.getWriter().equals(writer)) {
return update.getDto();
}
}
update.setData(data.getData());
update.setTitle(data.getTitle());
update.setCreatedAt(LocalDateTime.now());
return update.getDto();
}
기본적으로 @Transactional 어노테이션을 붙이면 안의 엔티티는 영속화가 된다.
따라서 따로 save를 해주지 않았지만 데이터가 update된다.
'Spring Boot' 카테고리의 다른 글
| Spring Boot Exception Handling (0) | 2024.12.17 |
|---|---|
| JPA란? (0) | 2024.12.01 |
| JPA Paging (0) | 2024.11.28 |
| JPQL (0) | 2024.11.28 |
| Spring Cloud Eureka (0) | 2024.10.29 |