[Spring boot] 유저정보 리턴 (1차)

유존돌돌이·2022년 2월 20일
0

Spring boot

목록 보기
9/20
post-thumbnail
  1. @PathVariable : 주소값에 있는 데이터를 변수로 가져온다.
    • @RequestParm은 직접 전달받은 Param값이다.
  2. findById(param)
    • JpaRepository로 데이터를 가져온다.
    • param값으로 조회했는데 없는 경우 Exception처리를 한다.
    • 만약 무조건 있는 값이라면 get()을 쓰지만 혹시 모르니까
  3. Return (MessageConverter)
    • 아래의 경우 User 객체로 리턴을 하면 자동으로 Json형식으로 보여준다.(@RestController의 리턴 웹브라우저에서)
// {id}주소로 파라미터 전달 받을 수 있음.
	@GetMapping("/dummy/user/{id}")
	public User detail(@PathVariable int id) {
		// findById의 형태는 Optional이다.
		// 왜냐?아이디 값으로 조회했는데null값이면 빈 객체로 인해 오류 발생할 수 있으니
		// Optional 값으로 줄테니 니가 알아서 걸러서 써
		User user = userRepository.findById(id).orElseThrow(new Supplier<IllegalArgumentException>(){
			@Override
			public IllegalArgumentException get() {
				return new IllegalArgumentException("해당 유저는 없습니다. ID: "+id);
			}
		});
		//(Lambda)
		//User user = userRepository.findById(id).orElseThrow(()->{
		//return new IllegalArgumentException("해당 유저는 없습니다. ID: "+id);
		//});
		
		// Spring boot의 MessageConverter	가Jackson 라이브러리 호출해서 json 형식으로 자동 리턴시켜준다.
		return user;
	}

0개의 댓글