TIL

스프링 데이터 JPA 분석

스프링 데이터 JPA 구현체 분석

@Repository
@Transactional(readOnly = true)
public class SimpleJpaRepository<T, ID> implements JpaRepositoryImplementation<T, ID> {
    @Transactional
    @Override
    public <S extends T> S save(S entity) {
        // ...
    }
}

읽기 전용 쿼리의 성능 최적화

엔티티가 영속성 컨텍스트에 관리되면 1차 캐시부터 변경 감지까지 얻을 수 있다. 하지만 스냅샷을 보관하는 등 더 많은 메모리를 사용하는 단점이 있다. 이를 해결하는 방법이 있다.

매우 중요!!! save()

save() 메서드*

if (entityInformation.isNew(entity)) {
    em.persist(entity);
    return entity;
} else {
    return em.merge(entity);
}

새로운 엔티티를 구별하는 방법

entityInformation.isNew(entity)

    @EntityListeners(AuditingEntityListener.class)
    @NoArgsConstructor(access = AccessLevel.PROTECTED)
    public class Item implements Persistable<String> {
    		@Id
    		private String id;
  
    		@CreatedDate
    		private LocalDateTime createdDate;
    		
    		public Item(String id) {
    		    this.id = id;
    		}
    
    		@Override
    		public String getId() {
    		    return id;
    		}
    
    		@Override
    		public boolean isNew() {
    		    return createdDate == null;
    		}
    }