728x90
낙관적 락 vs 비관적 락
한 자원에 여러 사용자가 접근할 경우 충돌을 방지하거나 데이터의 무결성을 보장하기 위해 동시성 제어가 필요합니다.
JPA가 지원하는 동시성 제어 방법으로 낙관적 락, 비관적 락이 있습니다.
낙관적 락(Optimistic Lock)
낙관적 락은 충돌이 발생하는 경우에만 동시성 문제를 해결합니다. 여러 사용자가 동시에 접근하는 것을 허용하며, 충돌이 발생하는 경우에만 락을 통해 해결하는 것입니다. 낙관적 락은 데이터베이스에서 락을 사용하지 않고, 어플리케이션에서 락을 처리함으로써 성능을 개선할 수 있습니다.
비관적 락(Pessimistic Lock)
비관적 락은 충돌을 예방하기 위해 사용자들의 동시 접근을 막습니다. 즉, 동시성을 제한하기 때문에 리소스에 접근하는 사용자가 락을 획득하면, 락을 풀때까지 다른 사용자들은 접근할 수 없습니다. 그러므로 비교적 성능이 저하됩니다.
Jpa @Version
JPA에서 @Version
애노테이션을 사용하여 엔티티의 버전 관리를 할 수 있습니다. 이를 통해 낙관적인 락(Optimistic Lock)을 구현할 수 있습니다.
@Version
애노테이션은 엔티티 클래스의 필드에 적용되며, 해당 필드는 엔티티의 버전 정보를 저장합니다. 버전 정보는 데이터베이스 테이블에 대응하는 필드와 함께 업데이트됩니다.
버전 정보는 다음 조건을 충족해야 합니다.
- 각 엔티티 클래스에는 버전 특성이 하나만 존재해야 합니다.
- 여러 테이블에 매핑된 엔티티의 기본 테이블에 배치해야 합니다.
- 버전 속성의 유형은 int, Integer, long, Long, short, Short, java.sql.Timestamp 중 하나여야 합니다.
버전 속성은 엔티티가 영속화될 때 초기값으로 설정되고, 상태 변경(수정)이 발생할 때마다 자동으로 증가합니다.
충돌 처리 방식
JPA가 버전 정보를 통해 충돌을 인지하고 처리하는 방식은 다음과 같습니다.
- 엔티티를 데이터베이스에 저장할 때, 엔티티의 버전 값과 데이터베이스의 버전 값을 비교합니다.
- 만약 버전 속성 값이 일치한다면 충돌이 일어나지 않은 것으로 업데이트를 진행합니다.
- 버전 속성 값이 일치하지 않다면, 충돌로 간주하고 예외가 발생합니다.
JpaOptimisticLockingFailureException
개발자는 충돌이 발생할 경우, 적절한 방식으로 충돌을 해결할 수 있습니다.
- 엔티티를 다시 조회한 후 수정 진행
- 사용자에게 다시 시도할 것을 요청하기
- 두 변경 내용을 병합
728x90
'BackEnd > Spring' 카테고리의 다른 글
[Spring/JPA] JPA 연관관계에서 지연 로딩과 즉시 로딩 (2) | 2024.02.04 |
---|---|
[Spring] Kotlin + Spring boot 프로젝트에 Redis 적용 (1) | 2023.03.14 |
[Spring] 스프링 요청 파라미터 - Reqeust Param (required, defaultValue) (0) | 2022.12.12 |
[Spring] 로깅 logging (0) | 2022.12.12 |
[Spring] 스프링 MyBatis 연동 (0) | 2022.11.01 |