Home ๐Ÿ” isPresent()๋ฅผ orElseThrow()๋กœ ๋ฐ”๊พธ๊ธฐ
Post
Cancel

๐Ÿ” isPresent()๋ฅผ orElseThrow()๋กœ ๋ฐ”๊พธ๊ธฐ



isPresent() ์‚ฌ์šฉ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	private Member getMemberIfExists() {

		// ์ด๋ฏธ ์ƒ์„ฑ๋˜์–ด ์žˆ๋Š” SecurityUtil์— getCurrentUsername()๋ฅผ ๊ฐ€์ž…๋œ ์ด๋ฉ”์ผ์ธ์ง€ ๊ฒ€์ฆํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ
		Optional<String> emailOptional = SecurityUtil.getCurrentUsername();

		if (emailOptional.isPresent()) { // ๊ฐ์ฒด ์กด์žฌ์—ฌ๋ถ€๋ฅผ ํ™•์ธ

			String email = emailOptional.get();
			Optional<Member> memberOptional = memberRepository.findByEmail(email);

			// ๊ฐ€์ž…ํ•œ ๋ฉค๋ฒ„๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ2 : ๋น„์–ด ์žˆ์„ ๋•Œ
			if (memberOptional.isEmpty()) {
				throw new MemberInfoNotExistException();
			} else return memberOptional.get();

		// ๊ฐ€์ž…ํ•œ ๋ฉค๋ฒ„๊ฐ€ ์•„๋‹ ๊ฒฝ์šฐ1 : ์กด์žฌํ•˜์ง€ ์•Š์„ ๋•Œ
		} else throw new MemberInfoNotExistException();
	}



orElseThrow() ์‚ฌ์šฉ

1
2
3
4
5
6
7
8
9
10
	private Member getMemberIfExists() {

  // ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ๋žŒ์ด ์žˆ์„ ๊ฒฝ์šฐ ํ•ด๋‹น ํšŒ์›์˜ email์„ ๊ฐ€์ ธ์˜จ๋‹ค.
  String email = SecurityUtil.getCurrentUserEmail().orElseThrow(()
  -> new MemberInfoNotExistException());

  // mysql์—์„œ ํ•ด๋‹น email์„ ๊ฐ€์ง„ ํšŒ์›์ด ์—†์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๋ฐœ์ƒ, ์žˆ์œผ๋ฉด ํšŒ์› ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค.
  return memberRepository.findByEmail(email).orElseThrow(()
  -> new MemberInfoNotExistException());
  }



๋žŒ๋‹ค๋กœ ๋ณ€๊ฒฝ

1
2
3
4
5
6
7
8
	private Member getMemberIfExists() {

		// ํ˜„์žฌ ๋กœ๊ทธ์ธํ•œ ์‚ฌ๋žŒ์ด ์žˆ์„ ๊ฒฝ์šฐ ํ•ด๋‹น ํšŒ์›์˜ email์„ ๊ฐ€์ ธ์˜จ๋‹ค.
		String email = SecurityUtil.getCurrentUserEmail().orElseThrow(MemberInfoNotExistException::new);

		// mysql์—์„œ ํ•ด๋‹น email์„ ๊ฐ€์ง„ ํšŒ์›์ด ์—†์„ ๊ฒฝ์šฐ ์˜ˆ์™ธ๋ฐœ์ƒ, ์žˆ์œผ๋ฉด ํšŒ์› ์ •๋ณด๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค.
		return memberRepository.findByEmail(email).orElseThrow(MemberInfoNotExistException::new);
	}



This post is licensed under CC BY 4.0 by the author.

/Java/ Entity์—์„œ ํ•„๋“œ๋‚˜ ์ปฌ๋Ÿผ์˜ ๊ธธ์ด์ œํ•œ ํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜

๐Ÿ” ๊ฒŒ์‹œ๋ฌผ ์‚ญ์ œ์‹œ ๋Œ“๊ธ€๋„ ํ•จ๊ป˜ ์‚ญ์ œ ๊ตฌํ˜„