반응형

유저의 프로필 화면에 유저가 등록한 이미지들을 보이게 할거다.

Userservice

-userProfile 메소드는 해당페이지 유저의 사진을 반환한다.
- findById로 매개변수로 넘어온 유저아이디로 유저를 찾는다. 
  만약 유저정보가 없다면 orElseThrow로 예외를 발동하고,  CustomException을 throw한다. 

@RequiredArgsConstructor
@Service
public class UserService {

    private final UserRepository userRepository;
    private final BCryptPasswordEncoder bCryptPasswordEncoder;

    @Transactional(readOnly = true)
    public UserProfileDto userProfile(int pageUserId, int principalId){

        UserProfileDto dto = new UserProfileDto();

        //SELECT * FROM image WHERE USERiD = :userId;
        User userEntity = userRepository.findById(pageUserId).orElseThrow(() -> {
            throw new CustomException("해당 프로필 페이지는 없는 페이지입니다.");
        }); 

        dto.setUser(userEntity);
        //pageUserId 와 principalId가 같은지 비교
        dto.setPageOwnerState(pageUserId == pageUserId);
        dto.setImageCount(userEntity.getImages().size());


        return dto;
    }

  ...
}

 

CustomException
- 에러 메시지만 받도록 한다. 

public class CustomException extends RuntimeException{

    private static final long serialVersionUID = 1L;

    public CustomException(String message){
        super(message);
    }

}

 

ControllerExceptionHandler

@RestController
@ControllerAdvice //모든 Exception들을 낚아챔
public class ControllerExceptionHandler {

...
    @ExceptionHandler(CustomException.class) //CustomValidationException 발동하는 모든 Exception을 이 함수가 가로챔
    public String exception(CustomException e){
       return  Script.back(e.getMessage());
    }

...
}

 

UserController

- user/profile 로 유저 정보 뿐만 아니라 유저와 연관된 이미지, 팔로우 정보도 가져가야 한다. 
- 그래서 user셀렉 할때 이미지 정보 등을 가져오게 해야하고, 이는 양방향 매핑으로 구현 가능하다.

@RequiredArgsConstructor
@Controller
public class UserController {

    private final UserService userService;

    @GetMapping({"/user/{pageUserId}"})
    public String profile(@PathVariable int pageUserId, Model model,
                          @AuthenticationPrincipal PrincipalDetails principalDetails){

        UserProfileDto dto = userService.userProfile(pageUserId, principalDetails.getUser().getId());

        model.addAttribute("dto", dto);
        return "user/profile";
    }

......
}

 

User
- mappedyBy:
1. 나는 연관관계의 주인이 아니다. 그러므로 테이블에 컬럼을 만들지마
2. User를 select할때 해당 유저 Id로 등록된 image들을 다 가져와

- OneToMany에서는 FetchType.LAZY이 기본 옵션
 1. Lazy = User를 SELECT할때 해당 유저 ID로 등록된 image들을 가져오지마
   대신 getImages()함수의 image들이호출될때 가져와!
 2. Eager = User를 SELECT할때 해당 유저 ID로 등록된 image들을 전부 Join해서 가져와!

@Builder
@AllArgsConstructor
@NoArgsConstructor  //Bean생성자
@Data
@Entity //DB에 테이블 생성
public class User {
    ...
 
    @OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
    @JsonIgnoreProperties({"user"}) //Image내부에 있는 user를 무시하고 파싱한다.
    private List<Image> images;

  ...
}

+ Recent posts