스프링/스프링 입문 - 김영한

10. 회원 서비스 개발

서견 2023. 1. 10. 00:18

IntelliJ 단축키

 

soutv : value를 바로 sysout 하는 기능

실행취소 (redo) : Ctrl + Shift + z

Rename : Shift + F6

변수추출 : Ctrl + Shft + v 

 

회원 서비스 작성

package hello.hellospring.service;

import hello.hellospring.domain.Member;
import hello.hellospring.repository.MemberRepository;
import hello.hellospring.repository.MemoryMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional
public class MemberService {

    private final MemberRepository memberRepository;
    public MemberService(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }

    //회원가입
    public Long join(Member member) {

        //같은 이름이 있는 중복 회원 X
            validateDuplicateMember(member); //중복 회원 검증
            memberRepository.save(member);
            return member.getId();

        }


    private void validateDuplicateMember(Member member) {
        memberRepository.findByName(member.getName())
                .ifPresent(m -> {
                    throw new IllegalStateException("이미 존재하는 회원입니다.");
                });
    }

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

    }

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