Programming/Spring,JPA

[JPA] 영속성 컨텍스트(Persistence Context) 내부 구조 살펴보기

우니wooni 2024. 10. 25. 20:11

StatefulPersistenceContext

PersistenceContext 인터페이스의 구현체로 이 구현은 영속성 컨텍스트가 해당 세션의 생명 주기 동안 엔티티의 상태를 유지하고 관리한다.

 

 

HashMap 구조

영속성 컨텍스트의 1차 캐시는 HashMap 구조이다. 1차 캐시에 관한 그림을 살펴보면 엔티티의 식별자를 Key로 사용한다고 알려져있다.

 

 

StatefulPersistenceContext 클래스

 

StatefulPersistenceContext 클래스를 살펴보면, Key 값으로 EntityKey 객체를 사용하고 있다. 해당 객체 안에 식별자가 존재할것으로 추측할 수 있다.

 

 

EntityKey 클래스

public final class EntityKey implements Serializable {

	private final Serializable identifier;
	private final int hashCode;
	private final EntityPersister persister;

	public EntityKey(Serializable id, EntityPersister persister) {
		this.persister = persister;
		if ( id == null ) {
			throw new AssertionFailure( "null identifier" );
		}
		this.identifier = id;
		this.hashCode = generateHashCode();
	}
	
	// ...
}

 

실제 구현을 확인해보니 identifier가 클래스 내부에 존재하는 것을 확인할 수 있다.

 


Entity를 영속성 컨텍스트에 저장하는 법

addEntity() 메소드

@Override
public void addEntity(EntityKey key, Object entity) {
	if ( entitiesByKey == null ) {
		entitiesByKey = new HashMap<>( INIT_COLL_SIZE );
	}
	entitiesByKey.put( key, entity );
	final BatchFetchQueue fetchQueue = this.batchFetchQueue;
	if ( fetchQueue != null ) {
		fetchQueue.removeBatchLoadableEntityKey( key );
	}
}

 

1차 캐시에 영속성 컨텍스트를 저장하는 메서드이다. 위에서 살펴본 HashMap entitiesByKey 에 고유 식별자를 Key로 사용하여 등록한다.

 

Entity를 조회하는 방법

getEntity() 메소드

@Override
public Object getEntity(EntityKey key) {
	return entitiesByKey == null ? null : entitiesByKey.get( key );
}