FireDrago
[JPA] @PersistenceContext 사용해야 하는 이유 본문
@Repository
public class MemberRepository {
@PersistenceContext
private EntityManager em;
위 코드 처럼 스프링에서 JPA를 사용할때 EntityManager는 @PersistenceContext 를 사용해서 주입받는다.
@Autowired 를 사용하지 않는 이유가 있을까?
1. @Autowired 는 스레드에 안전하지 않다.
여러 사용자가 영속성 컨텍스트를 공유할 위험이 생긴다.
@PersistenceContext 는 트랜잭션이 이미 사용중인 EntityManager 가 있다면 기존 EntityManager를,
없다면 EntityManagerFactory 를 통해 신규 EntityManager를 생성하여 주입해준다.
스레드 공유의 위험성을 없애주는 것이다.
Spring에서 @PersistenceContext의 동작 원리
Spring에서 xml이나 annotation을 이용한 component-scan에 의해서 등록되는 Bean중에서 @PersistenceContext의 동작원리는 다음과 같습니다.ComponentScanBeanDefinitionParserComponentScanBeanDefinitionParser.registerComponents를 통
netframework.tistory.com
'프로그래밍 > JPA' 카테고리의 다른 글
| [Spring Data JPA] 스프링 데이터 JPA 사용하기 (0) | 2024.04.23 |
|---|---|
| [JPA] cascade는 언제 사용해야 할까? (0) | 2024.04.09 |
| [JPA] JPQL 기본문법 2 (0) | 2024.04.06 |
| [JPA] JPQL 기본문법 1 (0) | 2024.04.04 |
| [JPA] 연관관계 관리 (0) | 2024.04.01 |
