๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Server/Spring

ํšŒ์›๊ด€๋ฆฌ - ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ) 3. ํšŒ์› ์„œ๋น„์Šค ๊ฐœ๋ฐœํ•˜๊ธฐ

by kkkkk1023 2024. 8. 24.
๐Ÿ’ก ์„œ๋น„์Šค๋ž€, ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๊ณ„์ธต์„ ๋งํ•œ๋‹ค. ์ฆ‰, ์‚ฌ์šฉ์ž๋ฅผ ๋“ฑ๋กํ•˜๊ฑฐ๋‚˜ ์ฃผ๋ฌธ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์ด ์—ฌ๊ธฐ์— ๋‹ด๊ธด๋‹ค. ์ปจํŠธ๋กค๋Ÿฌ์—์„œ ์š”์ฒญ์„ ๋ฐ›์œผ๋ฉด, ์„œ๋น„์Šค๊ฐ€ ์ผ์„ ์ฒ˜๋ฆฌํ•˜๊ณ , ํ•„์š”ํ•˜๋ฉด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์™€ ์—ฐ๊ฒฐํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๊ฑฐ๋‚˜ ์ €์žฅํ•œ๋‹ค.

 

ํŒŒ์ผ ๊ฒฝ๋กœ: src/main/java/๋งŒ๋“  ํŒŒ์ผ๋ช…/service(๋งŒ๋“ค์–ด์•ผํ•จ)/MemberService

 

package section4.section4_spring.service;

import section4.section4_spring.domain.Member;
import section4.section4_spring.repository.MemberRepository;
import section4.section4_spring.repository.MemoryMemberRepository;

import java.util.List;
import java.util.Optional;

public class MemberService {
    private final MemberRepository memberRepository = new MemoryMemberRepository();


    //ํšŒ์›๊ฐ€์ž…
    public Long join(Member member) {
        //๊ฐ™์€ ์ด๋ฆ„์ด ์žˆ๋Š” ์ค‘๋ณต์€ ํšŒ์›๊ฐ€์ž… x
        Optional<Member> result = memberRepository.findByname(member.getName());
        result.ifPresent(m -> { //m์€ result ๊ฐ’์„ ์˜๋ฏธํ•œ๋‹ค. ๋žŒ๋‹ค์‹ ๋‚ด๋ถ€ ์ฝ”๋“œ๋Š” result ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ์‹คํ–‰ํ•˜๊ฒŒ ๋  ์ฝ”๋“œ์ด๋‹ค.
            throw new IllegalStateException("์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํšŒ์›์ž…๋‹ˆ๋‹ค."); //์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ๋ฉ”์‹œ์ง€๋ฅผ ์ „๋‹ฌ
        });

        memberRepository.save(member);
        return member.getId();
    }

    public List<Member> findMembers(){
       return memberRepository.findAll();
    }

    public Optional<Member> findOne(Long id) {
        return memberRepository.findById(id);
    }

}

 

 

์—ฌ๊ธฐ์„œ ๋‹ค๋ฅธ ์ฝ”๋“œ๋Š” ์–ด๋ ค์šธ ๊ฒƒ์ด ์—†๊ธฐ์— ํšŒ์›๊ฐ€์ž… ์ฝ”๋“œ๋งŒ ์‚ดํŽด๋ณด์ž.

 

result.ifPresent(m -> { //m์€ result ๊ฐ’์„ ์˜๋ฏธํ•œ๋‹ค. ๋žŒ๋‹ค์‹ ๋‚ด๋ถ€ ์ฝ”๋“œ๋Š” result ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด ์‹คํ–‰ํ•˜๊ฒŒ ๋  ์ฝ”๋“œ์ด๋‹ค.
    throw new IllegalStateException("์ด๋ฏธ ์กด์žฌํ•˜๋Š” ํšŒ์›์ž…๋‹ˆ๋‹ค."); //์˜ˆ์™ธ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๊ณ  ๋ฉ”์‹œ์ง€๋ฅผ ์ „๋‹ฌ
});

 

 

  • ifPresent
    • result ๋‚ด๋ถ€์— ๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธํ•˜๋Š” ๊ฒƒ
  • m -> { ... }
    • m์€ result ๊ฐ’ ์ž์ฒด๋ฅผ ์˜๋ฏธํ•œ๋‹ค. ๋žŒ๋‹ค์‹ ์ฝ”๋“œ๋Š” result ๊ฐ’์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ ์‹คํ–‰๋œ๋‹ค.