@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository){
this.userRepository = userRepository;
}
}
위 코드는 아래와 같다.
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
}
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public void setUserRepository(UserRepository userRepository){
this.userRepository = userRepository;
}
}
Optional<User> user = userRepository.findById(userId);
if (user.isPresent()) {
User user = userOptional.get();
// 값이 존재할 때의 로직
} else {
// 값이 존재하지 않을 때의 로직
}
User user = userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException("User not found"));
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class UpdateArticleDto {
private Long userId;
private Long articleId;
private String title;
private String contents;
...
}
@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class ResponseArticleDto {
private Long articleId;
private String title;
private String contents;
private String authorName;
private String authorProfileImage;
private List<String> tags;
private List<ResponseLikeDto> likes;
private List<ResponseCommentDto> comments;
private LocalDateTime createdAt;
private boolean isLiked;
public static ResponseArticleDto of(Long articleId, String title, String contents, String authorName, String authorProfileImage, List<String> tags, List<ResponseLikeDto> likes, List<ResponseCommentDto> comments, LocalDateTime createdAt, boolean isLiked) {
return new ResponseArticleDto(articleId, title, contents, authorName, authorProfileImage, tags, likes, comments, createdAt, isLiked);
}
public static ResponseArticleDto from(Article article, boolean isLiked) {
return ResponseArticleDto.of(
article.getId(),
article.getTitle(),
article.getContents(),
article.getUser().getName(),
article.getUser().getProfileImage(),
article.getArticleTags().stream().map(articleTag -> articleTag.getTag().getTagName()).collect(Collectors.toList()),
article.getLikes().stream().map(ResponseLikeDto::from).collect(Collectors.toList()),
article.getComments().stream().map(ResponseCommentDto::from).collect(Collectors.toList()),
article.getCreatedAt(),
isLiked
);
}
}
@Getter
@Builder
public class ResponseSimpleArticleDto {
private Long articleId;
private String title;
private String contents;
private String authorName;
private String authorProfileImage;
private int likesCount;
private int commentCount;
private LocalDateTime createdAt;
private boolean isLiked;
}
ResponseSimpleArticleDto articleDto = ResponseSimpleArticleDto.builder()
.articleId(1L)
.title("title")
.contents("content")
.authorName("name")
.authorProfileImage("profile.jpg")
.likesCount(10)
.commentCount(5)
.createdAt(LocalDateTime.now())
.isLiked(false)
.build();
@Transactional
어노테이션을 반드시 추가해야 한다.@Transactional(readOnly = true)
를 추가한다.private void validateUser(Long userId) {
if (!userRepository.existsById(userId))
throw new UserException(ResponseCode.USER_NOT_FOUND);
}
private User getUserById(Long userId) {
return userRepository.findById(userId).orElseThrow(() -> new UserException(ResponseCode.USER_NOT_FOUND));
}
// 유저가 구독한 태그 조회
@Transactional(readOnly = true)
public List<ResponseTagDto> getUserTags(Long userId) {
User user = getUserById(userId);
List<UserTag> tags = user.getUserTags();
List<ResponseTagDto> responseTagDtos = new ArrayList<>();
for(UserTag tag : tags) {
responseTagDtos.add(ResponseTagDto.from(tag));
}
return responseTagDtos;
}
for문을 통해 Entity를 Dto로 변환하기보단, 되도록이면 Java 8의 stream() 연산을 활용하자.
// 유저가 구독한 태그 조회
@Transactional(readOnly = true)
public List<ResponseTagDto> getUserTags(Long userId) {
User user = getUserById(userId);
return user.getUserTags().stream()
.map(ResponseTagDto::from)
.collect(Collectors.toList());
}
훨씬 간결해졌음을 알 수 있다.
이처럼 Entity → Dto 변환 과정은, for문보다는 람다식과 stream을 활용하여 최대한 짧고 간결하게 작성하자.