인프런 - 스프링 부트와 JPA 활용1 by 김영한 을 기반으로 작성된 글입니다.
실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
💻 코드
package jpabook.jpashop.repository;
package jpabook.jpashop.service;
import jpabook.jpashop.domain.Member;
import jpabook.jpashop.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class MemberService {
//값 변경 X - final
private final MemberRepository memberRepository;
/* 회원가입 */
public Long join(Member member){
validateDuplicatedMember(member); //중복 회원 검증
memberRepository.save(member);
return member.getId();
}
private void validateDuplicatedMember(Member member) {
List<Member> findMembers = memberRepository.findByName(member.getName());
if(!findMembers.isEmpty()){
throw new IllegalStateException("이미 존재하는 회원입니다");
}
; }
/* 회원 전체 조회 */
public List<Member> findMembers(){
return memberRepository.findAll();
}
/* 특정 회원 조회 */
public Member findOne(Long memberId){
return memberRepository.findOne(memberId);
}
}
👉 설명
1) 기술
@Transactional
: 트랜잭션, 영속성 컨텍스트@RequiredArgsConstructor
: final 필드만 생성자 생성2) 기능
public class MemberService {
@Autowired
private MemberRepository memberRepository;
…
}
public class MemberService {
private final MemberRepository memberRepository;
public MemberService(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
…
}
❗ 엔티티 매니저
@Autowired
뿐만 아니라 @PersistenceContext
표준 어노테이션 있어야 주입
그러나 스프링 데이터 JPA를 사용하면 @Autowired
만 사용해도 주입 가능
🧷 생성자 하나면, @Autowired
생략 가능
@AllArgsConstructor
사용 코드
@Service
@Transactional(readOnly = true)
@AllArgsConstructor
public class MemberService {
private final MemberRepository memberRepository;
…
}
@RequiredArgsConstructor
사용 코드
@Repository
@RequiredArgsConstructor
public class MemberService {
private final MemberRepository memberRepository;
…
}
@Repository
public class MemberRepository {
private final EntityManager em;
public MemberRepository(EntityManager em) {
this.em = em;
}
…
}
위의 코드를 아래처럼 사용 가능
@RequiredArgsConstructor
사용 코드@Repository
@RequiredArgsConstructor
public class MemberRepository {
private final EntityManager em;
…
}