이 저장소에 공개된 성능 레시피에 대해 자세히 알아보고 싶다면 내 책 "Spring Boot Persistence Best Practices"를 좋아하실 것이라고 확신합니다. | 100개 이상의 Java 지속성 성능 문제에 대한 팁과 그림이 필요한 경우 "Java Persistence Performance Illustrated Guide"가 적합합니다. |
최대 절전 모드 및 스프링 부트 샘플
설명: 이 애플리케이션은 날짜, 시간 및 타임스탬프를 UTC 시간대에 저장하는 방법에 대한 샘플입니다. 두 번째 설정인 useLegacyDatetimeCode
는 MySQL에만 필요합니다. 그렇지 않으면 hibernate.jdbc.time_zone
만 설정하십시오.
핵심 사항:
spring.jpa.properties.hibernate.jdbc.time_zone=UTC
spring.datasource.url=jdbc:mysql://localhost:3306/screenshotdb?useLegacyDatetimeCode=false
설명: Log4J 2 로거 설정을 통해 준비된 명령문 바인딩/추출된 매개변수를 봅니다.
핵심 사항:
pom.xml
에서 Spring Boot의 기본 로깅을 제외합니다.pom.xml
에서 Log4j 2 종속성을 추가합니다.log4j2.xml
에 <Logger name="org.hibernate.type.descriptor.sql" level="trace"/>
를 추가하세요.출력 예:
설명: DataSource-Proxy를 통해 쿼리 세부 정보(쿼리 유형, 바인딩 매개변수, 배치 크기, 실행 시간 등)를 봅니다.
핵심 사항:
pom.xml
에 datasource-proxy
종속성을 추가하세요.DataSource
빈을 가로채기 위해 빈 포스트 프로세서를 생성합니다.ProxyFactory
와 MethodInterceptor
구현을 통해 DataSource
빈을 래핑합니다. 출력 예:
saveAll(Iterable<S> entities)
통한 일괄 삽입 설명: MySQL의 SimpleJpaRepository#saveAll(Iterable<S> entities)
메서드를 통한 일괄 삽입
핵심 사항:
application.properties
에서 spring.jpa.properties.hibernate.jdbc.batch_size
설정하십시오.application.properties
에서 spring.jpa.properties.hibernate.generate_statistics
설정합니다(일괄 처리가 작동하는지 확인하기 위해).application.properties
에서 rewriteBatchedStatements=true
로 JDBC URL을 설정합니다(MySQL 최적화).application.properties
에서 JDBC URL을 cachePrepStmts=true
로 설정합니다(캐싱을 활성화하고 prepStmtCacheSize
, prepStmtCacheSqlLimit
등도 설정하기로 결정한 경우 유용합니다. 이 설정이 없으면 캐시가 비활성화됩니다).application.properties
에서 useServerPrepStmts=true
로 JDBC URL을 설정합니다(이렇게 하면 서버 측 준비된 명령문으로 전환할 수 있습니다(상당한 성능 향상으로 이어질 수 있음)).spring.jpa.properties.hibernate.order_inserts=true
설정하여 삽입을 주문하여 일괄 처리를 최적화하는 것을 고려하십시오.IDENTITY
로 인해 삽입 일괄 처리가 비활성화되므로 할당된 생성기를 사용합니다.@Version
속성을 추가하여 일괄 처리 전에 추가 SELECT
문이 실행되는 것을 방지합니다(또한 다중 요청 트랜잭션에서 업데이트 손실을 방지합니다). Extra- SELECT
문은 persist()
대신 merge()
사용하는 효과입니다. 이면에서, saveAll()
save()
사용하는데, 이는 새로운 엔터티(ID를 가진 엔터티)가 아닌 경우 merge()
호출하여 Hibernate에 SELECT
문을 실행하여 레코드가 없는지 확인하도록 지시합니다. 동일한 식별자를 가진 데이터베이스saveAll()
에 전달된 삽입의 양에 주의하세요. 일반적으로 EntityManager
수시로 플러시되고 지워져야 하지만 saveAll()
실행 중에는 그렇게 할 수 없습니다. 따라서 saveAll()
에 많은 양의 데이터가 포함된 목록이 있는 경우 해당 데이터는 모두 Persistence에 도달합니다. 컨텍스트(1단계 캐시)는 플러시 시간까지 메모리에 유지됩니다. 상대적으로 적은 양의 데이터를 사용해도 괜찮습니다(이 예에서는 30개의 엔터티로 구성된 각 배치가 별도의 트랜잭션 및 영구 컨텍스트에서 실행됩니다).saveAll()
메소드는 지속된 엔터티를 포함하는 List<S>
반환합니다. 각각의 지속된 엔터티가 이 목록에 추가됩니다. 이 List
이 필요하지 않으면 아무것도 생성되지 않습니다.spring.jpa.properties.hibernate.cache.use_second_level_cache=false
를 통해 두 번째 수준 캐시가 비활성화되어 있는지 확인하십시오. 설명: 이 애플리케이션은 MySQL의 EntityManager
통한 일괄 삽입 샘플입니다. 이 방법을 사용하면 현재 트랜잭션 내 지속성 컨텍스트(1단계 캐시)의 flush()
및 clear()
주기를 쉽게 제어할 수 있습니다. 이 메서드는 트랜잭션당 단일 플러시를 실행하므로 Spring Boot, saveAll(Iterable<S> entities)
를 통해서는 불가능합니다. 또 다른 장점은 merge()
대신 persist()
호출할 수 있다는 것입니다. 이는 SpringBoot saveAll(Iterable<S> entities)
및 save(S entity)
에 의해 배후에서 사용됩니다.
트랜잭션별로 일괄 처리를 실행하려면(권장) 이 예를 확인하세요.
핵심 사항:
application.properties
에서 spring.jpa.properties.hibernate.jdbc.batch_size
설정하십시오.application.properties
에서 spring.jpa.properties.hibernate.generate_statistics
설정합니다(일괄 처리가 작동하는지 확인하기 위해).application.properties
에서 rewriteBatchedStatements=true
로 JDBC URL을 설정합니다(MySQL 최적화).application.properties
에서 JDBC URL을 cachePrepStmts=true
로 설정합니다(캐싱을 활성화하고 prepStmtCacheSize
, prepStmtCacheSqlLimit
등도 설정하기로 결정한 경우 유용합니다. 이 설정이 없으면 캐시가 비활성화됩니다).application.properties
에서 useServerPrepStmts=true
로 JDBC URL을 설정합니다(이렇게 하면 서버 측 준비된 명령문으로 전환할 수 있습니다(상당한 성능 향상으로 이어질 수 있음)).spring.jpa.properties.hibernate.order_inserts=true
설정하여 삽입을 주문하여 일괄 처리를 최적화하는 것을 고려하십시오.IDENTITY
로 인해 삽입 일괄 처리가 비활성화되므로 할당된 생성기를 사용합니다.spring.jpa.properties.hibernate.cache.use_second_level_cache=false
를 통해 두 번째 수준 캐시가 비활성화되어 있는지 확인하십시오.출력 예:
설명: MySQL의 JpaContext/EntityManager
를 통해 일괄 삽입됩니다.
핵심 사항:
application.properties
에서 spring.jpa.properties.hibernate.jdbc.batch_size
설정하십시오.application.properties
에서 spring.jpa.properties.hibernate.generate_statistics
설정합니다(일괄 처리가 작동하는지 확인하기 위해).application.properties
에서 rewriteBatchedStatements=true
로 JDBC URL을 설정합니다(MySQL 최적화).application.properties
에서 JDBC URL을 cachePrepStmts=true
로 설정합니다(캐싱을 활성화하고 prepStmtCacheSize
, prepStmtCacheSqlLimit
등도 설정하기로 결정한 경우 유용합니다. 이 설정이 없으면 캐시가 비활성화됩니다).application.properties
에서 useServerPrepStmts=true
로 JDBC URL을 설정합니다(이렇게 하면 서버 측 준비된 명령문으로 전환할 수 있습니다(상당한 성능 향상으로 이어질 수 있음)).spring.jpa.properties.hibernate.order_inserts=true
설정하여 삽입을 주문하여 일괄 처리를 최적화하는 것을 고려하십시오.IDENTITY
로 인해 삽입 일괄 처리가 비활성화되므로 할당된 생성기를 사용합니다.EntityManager
는 JpaContext#getEntityManagerByManagedType(Class<?> entity)
를 통해 엔터티 유형별로 가져옵니다.spring.jpa.properties.hibernate.cache.use_second_level_cache=false
를 통해 두 번째 수준 캐시가 비활성화되어 있는지 확인하십시오.출력 예:
설명: MySQL에서 Hibernate 세션 수준 일괄 처리(Hibernate 5.2 이상)를 통해 일괄 삽입합니다.
핵심 사항:
application.properties
에서 spring.jpa.properties.hibernate.generate_statistics
설정합니다(일괄 처리가 작동하는지 확인하기 위해).application.properties
에서 rewriteBatchedStatements=true
로 JDBC URL을 설정합니다(MySQL 최적화).application.properties
에서 JDBC URL을 cachePrepStmts=true
로 설정합니다(캐싱을 활성화하고 prepStmtCacheSize
, prepStmtCacheSqlLimit
등도 설정하기로 결정한 경우 유용합니다. 이 설정이 없으면 캐시가 비활성화됩니다).application.properties
에서 useServerPrepStmts=true
로 JDBC URL을 설정합니다(이렇게 하면 서버 측 준비된 명령문으로 전환할 수 있습니다(상당한 성능 향상으로 이어질 수 있음)).spring.jpa.properties.hibernate.order_inserts=true
설정하여 삽입을 주문하여 일괄 처리를 최적화하는 것을 고려하십시오.IDENTITY
로 인해 삽입 일괄 처리가 비활성화되므로 할당된 생성기를 사용합니다.Session
EntityManager#unwrap(Session.class)
통해 래핑을 해제하여 얻습니다.Session#setJdbcBatchSize(Integer size)
를 통해 설정되고 Session#getJdbcBatchSize()
통해 가져옵니다.spring.jpa.properties.hibernate.cache.use_second_level_cache=false
를 통해 두 번째 수준 캐시가 비활성화되어 있는지 확인하십시오.출력 예:
findById()
, JPA EntityManager
및 Hibernate Session
통한 직접 가져오기 설명: Spring Data, EntityManager
및 Hibernate Session
예제를 통한 직접 가져오기.
핵심 사항:
findById()
사용합니다.EntityManager
통한 직접 가져오기는 find()
사용합니다.Session
통한 직접 가져오기는 get()
사용합니다.참고: "스프링 프로젝션을 통해 가상 속성으로 DTO를 강화하는 방법" 레시피를 읽어볼 수도 있습니다.
설명: DTO(Spring Data Projections)를 통해 데이터베이스에서 필요한 데이터만 가져옵니다.
핵심 사항:
List<projection>
을 반환하는 적절한 쿼리를 작성하세요.LIMIT
통해).참고: 프로젝션 사용은 Spring Data 저장소 인프라에 내장된 쿼리 빌더 메커니즘을 사용하는 것으로 제한되지 않습니다. JPQL이나 기본 쿼리를 통해서도 예측을 가져올 수 있습니다. 예를 들어 이 애플리케이션에서는 JPQL을 사용합니다.
출력 예(처음 2개 행 선택, "이름" 및 "나이"만 선택):
이 저장소에 공개된 성능 레시피에 대해 자세히 알아보고 싶다면 내 책 "Spring Boot Persistence Best Practices"를 좋아하실 것이라고 확신합니다. | 100개 이상의 Java 지속성 성능 문제에 대한 팁과 그림이 필요한 경우 "Java Persistence Performance Illustrated Guide"가 적합합니다. |
설명: 기본적으로 엔터티의 속성은 즉시(한 번에) 로드됩니다. 하지만 게으른 로드도 가능합니다. 이는 대량의 데이터( CLOB
, BLOB
, VARBINARY
등)를 저장하거나 요청 시 로드해야 하는 세부 정보를 저장하는 열 유형에 유용합니다. 이 애플리케이션에는 Author
라는 엔터티가 있습니다. 해당 속성은 id
, name
, genre
, avatar
및 age
입니다. 그리고 우리는 avatar
를 게으르게 로드하고 싶습니다. 따라서 avatar
요청 시 로드되어야 합니다.
핵심 사항:
pom.xml
에서 Hibernate 바이트코드 향상을 활성화합니다(예: Maven 바이트코드 향상 플러그인 사용).@Basic(fetch = FetchType.LAZY)
사용하여 지연 로드되어야 하는 속성에 주석을 답니다.application.properties
에서 보기에서 세션 열기를 비활성화합니다. 다음 사항도 확인하세요.
- 지연 로드 속성의 기본값
- 속성 지연 로딩 및 Jackson 직렬화
설명: Hibernate 프록시는 하위 엔터티가 상위 엔터티( @ManyToOne
또는 @OneToOne
연결)에 대한 참조로 지속될 수 있을 때 유용할 수 있습니다. 그러한 경우 데이터베이스에서 상위 엔터티를 가져오는 것( SELECT
문 실행)은 성능 저하이고 무의미한 작업입니다. 왜냐하면 Hibernate는 초기화되지 않은 프록시에 대한 기본 외래 키 값을 설정할 수 있기 때문입니다.
핵심 사항:
EntityManager#getReference()
에 의존JpaRepository#getOne()
->을 사용합니다.load()
사용합니다.@ManyToOne
연결에 관련된 두 엔터티 Author
및 Book
가정합니다( Author
는 상위 측임).SELECT
가 실행되지 않음), 새 책을 만들고, 프록시를 이 책의 저자로 설정하고 책을 저장합니다(이렇게 하면 book
테이블에서 INSERT
가 실행됩니다).출력 예:
INSERT
만 트리거되고 SELECT
없음이 표시됩니다.설명: N+1은 지연 가져오기 문제입니다(그러나 열망도 예외는 아닙니다). 이 응용 프로그램은 N+1 동작을 재현합니다.
핵심 사항:
@OneToMany
연관에서 Author
와 Book
두 개의 엔터티를 정의합니다.Book
게으르게 가져오므로 Author
없습니다(쿼리 1개 발생)Book
컬렉션을 반복하고 각 항목에 대해 해당 Author
가져옵니다(N 쿼리 결과)Author
게으르게 가져오므로 Book
없습니다(결과적으로 쿼리 1개 발생).Author
컬렉션을 반복하고 각 항목에 대해 해당 Book
가져옵니다(N개의 쿼리 결과) 출력 예:
HINT_PASS_DISTINCT_THROUGH
힌트를 통해 SELECT DISTINCT
최적화 설명: Hibernate 5.2.2부터 HINT_PASS_DISTINCT_THROUGH
힌트를 통해 SELECT DISTINCT
유형의 JPQL(HQL) 쿼리 항목을 최적화할 수 있습니다. 이 힌트는 JPQL(HQL) JOIN FETCH 쿼리에만 유용하다는 점을 명심하세요. 스칼라 쿼리(예: List<Integer>
), DTO 또는 HHH-13280에는 유용하지 않습니다. 이러한 경우 기본 SQL 쿼리에 DISTINCT
JPQL 키워드를 전달해야 합니다. 이는 결과 집합에서 중복 항목을 제거하도록 데이터베이스에 지시합니다.
핵심 사항:
@QueryHints(value = @QueryHint(name = HINT_PASS_DISTINCT_THROUGH, value = "false"))
사용 출력 예:
참고: Hibernate Dirty Checking 메커니즘은 플러시 시 엔터티 수정 사항을 식별하고 우리를 대신하여 해당 UPDATE
문을 트리거하는 역할을 합니다.
설명: Hibernate 버전 5 이전에는 Dirty Checking 메커니즘이 모든 관리 엔터티의 모든 속성을 확인하기 위해 Java Reflection API를 사용했습니다. Hibernate 버전 5부터 Dirty Checking 메커니즘은 Hibernate Bytecode Enhancement가 애플리케이션에 존재하도록 요구하는 Dirty Tracking 메커니즘(자체 속성 변경을 추적하는 엔터티의 기능)에 의존할 수 있습니다. Dirty Tracking 메커니즘은 특히 엔터티 수가 비교적 많은 경우 더 나은 성능을 유지합니다.
Dirty Tracking 의 경우 바이트코드 향상 프로세스 중에 엔티티 클래스 바이트코드는 추적기 $$_hibernate_tracker
추가하여 Hibernate에 의해 계측됩니다. 플러시 시간에 Hibernate는 이 추적기를 사용하여 엔터티 변경 사항을 발견합니다(각 엔터티 추적기는 변경 사항을 보고합니다). 이는 모든 관리 엔터티의 모든 속성을 확인하는 것보다 낫습니다.
일반적으로(기본적으로) 계측은 빌드 시 발생하지만 런타임이나 배포 시에도 발생하도록 구성할 수 있습니다. 런타임 시 오버헤드를 피하기 위해 빌드 시에 수행하는 것이 좋습니다.
바이트코드 향상 추가 및 더티 트래킹 활성화는 Maven 또는 Gradle을 통해 추가된 플러그인을 통해 수행할 수 있습니다(Ant도 사용할 수 있음). 우리는 Maven을 사용하므로 pom.xml
에 추가합니다.
핵심 사항:
pom.xml
파일에 Bytecode Enhancement 플러그인을 추가하세요. 출력 예:
바이트코드 향상 효과는 여기 Author.class
에서 볼 수 있습니다. $$_hibernate_tracker
사용하여 바이트코드가 어떻게 계측되었는지 확인하세요.
Optional
사용 설명: 이 애플리케이션은 엔터티 및 쿼리에서 Java 8 Optional
사용하는 것이 올바른 방법을 보여주는 예입니다.
핵심 사항:
Optional
반환하는 Spring Data 내장 쿼리 메서드를 사용하세요(예: findById()
)Optional
반환하는 쿼리를 직접 작성하세요.Optional
사용data-mysql.sql
파일을 확인하세요.@OneToMany
양방향 연결을 매핑하는 가장 좋은 방법 설명: 이 애플리케이션은 성능 관점에서 양방향 @OneToMany
연결을 구현하는 것이 올바른 방법에 대한 개념 증명입니다.
핵심 사항:
mappedBy
사용하세요.orphanRemoval
사용하세요.@NaturalId
)) 및/또는 데이터베이스 생성 식별자를 사용하고 여기에서와 같이 equals()
및 hashCode()
메서드를 (자식 측에서) 적절하게 재정의합니다.toString()
재정의해야 하는 경우 엔터티가 데이터베이스에서 로드될 때 가져온 기본 속성만 포함하도록 주의하세요. 참고: 제거 작업, 특히 하위 엔터티 제거에 주의하세요. CascadeType.REMOVE
및 orphanRemoval=true
너무 많은 쿼리를 생성할 수 있습니다. 이러한 시나리오에서는 대량 작업에 의존하는 것이 대부분 삭제를 위한 가장 좋은 방법입니다.
설명: 이 애플리케이션은 JpaRepository
, EntityManager
및 Session
통해 쿼리를 작성하는 방법의 예입니다.
핵심 사항:
JpaRepository
의 경우 @Query
또는 Spring 데이터 쿼리 생성을 사용하세요.EntityManager
및 Session
의 경우 createQuery()
메소드를 사용하십시오.AUTO
생성기 유형을 피하는 이유와 방법 설명: MySQL 및 Hibernate 5에서 GenerationType.AUTO
생성기 유형은 TABLE
생성기를 사용하게 됩니다. 이는 상당한 성능 저하를 추가합니다. GenerationType.IDENTITY
또는 기본 생성기를 사용하여 이 동작을 IDENTITY
생성기로 전환할 수 있습니다.
핵심 사항:
GenerationType.AUTO
대신 GenerationType.IDENTITY
사용하세요. 출력 예:
설명: 이 응용 프로그램은 엔터티에 대한 save()
호출이 중복되는 경우(필요하지 않음)의 예입니다.
핵심 사항:
save()
메소드를 명시적으로 호출할 필요 없이 자동으로 해당 UPDATE
문을 트리거합니다.save()
호출)은 트리거된 쿼리 수에 영향을 미치지 않지만 기본 Hibernate 프로세스의 성능 저하를 의미합니다.이 저장소에 공개된 성능 레시피에 대해 자세히 알아보고 싶다면 내 책 "Spring Boot Persistence Best Practices"를 좋아하실 것이라고 확신합니다. | 100개 이상의 Java 지속성 성능 문제에 대한 팁과 그림이 필요한 경우 "Java Persistence Performance Illustrated Guide"가 적합합니다. |
BIG
) SERIAL
피하는 이유 설명: PostgreSQL에서 GenerationType.IDENTITY
사용하면 삽입 일괄 처리가 비활성화됩니다. (BIG)SERIAL
은 MySQL, AUTO_INCREMENT
와 "거의" 비슷하게 작동합니다. 이 애플리케이션에서는 삽입 일괄 처리를 허용하는 GenerationType.SEQUENCE
사용하고 hi/lo
최적화 알고리즘을 통해 이를 최적화합니다.
핵심 사항:
GenerationType.IDENTITY
대신 GenerationType.SEQUENCE
사용하세요.hi/lo
알고리즘을 사용하여 데이터베이스 왕복에서 hi 값을 가져옵니다( hi 값은 메모리 내에서 특정/주어진 수의 식별자를 생성하는 데 유용합니다. 모든 메모리 내 식별자를 모두 사용하기 전까지는 필요하지 않습니다. 또 다른 인사 를 받으러 )pooled
및 pooled-lo
식별자 생성기를 사용할 수 있습니다(이것은 외부 서비스가 중복 키 오류를 일으키지 않고 데이터베이스를 사용할 수 있도록 허용하는 hi/lo
의 최적화입니다).spring.datasource.hikari.data-source-properties.reWriteBatchedInserts=true
를 통해 일괄 처리 최적화 출력 예:
SINGLE_TABLE
설명: 이 애플리케이션은 JPA 단일 테이블 상속 전략( SINGLE_TABLE
)을 사용하는 샘플입니다.
핵심 사항:
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
).@NotNull
및 MySQL 트리거를 통해 하위 클래스 속성의 null 허용 여부가 보장됩니다.TINYINT
유형으로 선언하여 최적화되었습니다. 출력 예(아래는 3개 엔터티에서 얻은 단일 테이블입니다):
설명: 이 애플리케이션은 "무대 뒤에서" 트리거된 SQL 문을 계산하고 어설션하는 샘플입니다. 코드가 생각하는 것보다 더 많은 SQL 문을 생성하지 않도록 하기 위해 SQL 문 수를 계산하는 데 매우 유용합니다(예: 예상 문 수를 지정하여 N+1을 쉽게 감지할 수 있음).
핵심 사항:
pom.xml
에서 DataSource-Proxy 라이브러리 및 Vlad Mihalcea의 db-util 라이브러리에 대한 종속성을 추가합니다.countQuery()
사용하여 ProxyDataSourceBuilder
만듭니다.SQLStatementCountValidator.reset()
을 통해 카운터를 재설정합니다.assertInsert/Update/Delete/Select/Count(long expectedNumberOfSql)
를 통해 INSERT
, UPDATE
, DELETE
및 SELECT
주장합니다. 출력 예(예상 SQL 수가 실제와 같지 않으면 예외가 발생함):
설명: 이 애플리케이션은 JPA 콜백( Pre/PostPersist
, Pre/PostUpdate
, Pre/PostRemove
및 PostLoad
) 설정 샘플입니다.
핵심 사항:
void
반환하고 인수를 취하지 않아야 합니다. 출력 예:
@OneToOne
관계에서 식별자를 공유하기 위해 @MapsId
사용하는 방법 설명: 일반적인 단방향/양방향 @OneToOne
대신 단방향 @OneToOne
및 @MapsId
사용하는 것이 좋습니다. 이 응용 프로그램은 개념 증명입니다.
핵심 사항:
@MapsId
사용@JoinColumn
사용하십시오.@OneToOne
연결의 경우 @MapsId
기본 키를 상위 테이블과 공유합니다( id
속성은 기본 키와 외래 키 역할을 모두 수행함).메모:
@MapsId
@ManyToOne
에도 사용할 수 있습니다.SqlResultSetMapping
및 EntityManager
통해 DTO를 가져오는 방법 설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 SqlResultSetMapping
및 EntityManager
사용합니다.
핵심 사항:
SqlResultSetMapping
및 EntityManager
사용SqlResultSetMapping
및 NamedNativeQuery
통해 DTO를 가져오는 방법 참고: 기본 명명된 쿼리와 동일한 이름을 가진 저장소 인터페이스 메서드를 간단히 생성하기 위해 {EntityName}.{RepositoryMethodName}
명명 규칙을 사용하려면 이 애플리케이션을 건너뛰고 이 애플리케이션을 확인하세요.
설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 SqlResultSetMapping
, NamedNativeQuery
사용합니다.
핵심 사항:
SqlResultSetMapping
, NamedNativeQuery
사용javax.persistence.Tuple
및 기본 SQL을 통해 DTO를 가져오는 방법 설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 javax.persistence.Tuple
및 기본 SQL을 사용합니다.
핵심 사항:
java.persistence.Tuple
사용하고 쿼리를 nativeQuery = true
로 표시합니다.javax.persistence.Tuple
및 JPQL을 통해 DTO를 가져오는 방법 설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 javax.persistence.Tuple
및 JPQL을 사용합니다.
핵심 사항:
java.persistence.Tuple
사용하십시오.설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 생성자 표현식과 JPQL을 사용합니다.
핵심 사항:
SELECT new com.bookstore.dto.AuthorDto(a.name, a.age) FROM Author a
로 사용합니다. 참조:
생성자 및 Spring 데이터 쿼리 빌더 메커니즘을 통해 DTO를 가져오는 방법
이 저장소에 공개된 성능 레시피에 대해 자세히 알아보고 싶다면 내 책 "Spring Boot Persistence Best Practices"를 좋아하실 것이라고 확신합니다. | 100개 이상의 Java 지속성 성능 문제에 대한 팁과 그림이 필요한 경우 "Java Persistence Performance Illustrated Guide"가 적합합니다. |
ResultTransformer
및 기본 SQL을 통해 DTO를 가져오는 방법 설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하될 수 있습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 Hibernate, ResultTransformer
및 기본 SQL을 사용합니다.
핵심 사항:
AliasToBeanConstructorResultTransformer
사용합니다.Transformers.aliasToBean()
사용하십시오.EntityManager.createNativeQuery()
및 unwrap(org.hibernate.query.NativeQuery.class)
사용하십시오.ResultTransformer
더 이상 사용되지 않지만 대체품이 가능할 때까지(아마도 Hibernate 6.0에서) 사용할 수 있습니다(자세히 읽어보세요)ResultTransformer
및 JPQL을 통해 DTO를 가져오는 방법 설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하될 수 있습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 Hibernate, ResultTransformer
및 JPQL을 사용합니다.
핵심 사항:
AliasToBeanConstructorResultTransformer
사용합니다.Transformers.aliasToBean()
사용하십시오.EntityManager.createQuery()
및 unwrap(org.hibernate.query.Query.class)
사용하십시오.ResultTransformer
더 이상 사용되지 않지만 대체품이 사용 가능해질 때까지(Hibernate 6.0에서) 사용할 수 있습니다(자세히 읽어보세요)설명: 필요한 것보다 더 많은 데이터를 가져오면 성능이 저하되기 쉽습니다. DTO를 사용하면 필요한 데이터만 추출할 수 있습니다. 이 애플리케이션에서는 Blaze-Persistence 엔터티 뷰를 사용합니다.
핵심 사항:
pom.xml
에 추가합니다.CriteriaBuilderFactory
및 EntityViewManager
를 통해 Blaze-Persistence 구성EntityViewRepository
확장하여 Spring 중심 저장소 작성findAll()
, findOne()
등과 같은 이 저장소의 호출 메소드@ElementCollection
( @OrderColumn
제외)의 작동 방식 설명: 이 애플리케이션은 @ElementCollection
사용 시 발생할 수 있는 성능 저하를 보여줍니다. 이 경우에는 @OrderColumn
이 없습니다. 다음 항목(34)에서 볼 수 있듯이 @OrderColumn
추가하면 일부 성능 저하를 완화할 수 있습니다.
핵심 사항:
@ElementCollection
에는 기본 키가 없습니다.@ElementCollection
은 별도의 테이블에 매핑됩니다.@ElementCollection
사용하지 마세요. 삽입/삭제는 Hibernate가 기존 테이블 행을 모두 삭제하고, 메모리 내에서 컬렉션을 처리하고, 메모리에서 컬렉션을 미러링하기 위해 나머지 테이블 행을 다시 삽입하도록 합니다. 출력 예:
@OrderColumn
사용한 @ElementCollection
의 작동 방식 설명: 이 애플리케이션은 @ElementCollection
사용으로 인한 성능 저하를 보여줍니다. 이 경우에는 @OrderColumn
사용합니다. 그러나 이 애플리케이션에서 볼 수 있듯이(항목 33과 비교) @OrderColumn
추가하면 컬렉션 테일 근처에서 작업이 발생할 때 일부 성능 저하를 완화할 수 있습니다(예: 컬렉션 끝에서 추가/제거). 주로 추가/제거 항목 앞에 있는 모든 요소는 그대로 유지되므로 컬렉션 꼬리에 가까운 행에 영향을 미치면 성능 저하를 무시할 수 있습니다.
핵심 사항:
@ElementCollection
에는 기본 키가 없습니다.@ElementCollection
은 별도의 테이블에 매핑됩니다.@OrderColumn
이 있는 @ElementCollection
선호합니다. 출력 예:
참고: 이 항목을 읽기 전에 Hibernate5Module이 당신이 찾고 있는 것이 아닌지 확인하십시오.
설명: View 안티 패턴의 Open-Session은 SpringBoot에서 기본적으로 활성화됩니다. 이제 Author
와 Book
(저자는 더 많은 책을 연결했습니다)이라는 두 엔터티 사이의 지연 연결(예: @OneToMany
)을 상상해 보세요. 다음으로 REST 컨트롤러 엔드포인트는 연결된 Book
없이 Author
를 가져옵니다. 그러나 View(보다 정확하게는 Jackson)는 관련 Book
의 지연 로딩도 강제로 수행합니다. OSIV는 이미 열려 있는 Session
제공하므로 프록시 초기화가 성공적으로 수행됩니다. 이러한 성능 저하를 방지하는 솔루션은 OSIV를 비활성화하는 것부터 시작됩니다. 또한 가져오지 않은 지연 연결을 명시적으로 초기화합니다. 이렇게 하면 뷰가 지연 로딩을 강제하지 않습니다.
핵심 사항:
application.properties
에 다음 설정을 추가하여 OSIV를 비활성화합니다: spring.jpa.open-in-view=false
Author
엔터티를 가져오고 연관된 Book
(기본값) 값(예: null
)으로 명시적으로 초기화합니다.null
렌더링이나 결과 JSON에서 비어 있는 것으로 간주되는 것을 방지하려면 이 엔터티 수준에서 @JsonInclude(Include.NON_EMPTY)
설정하세요. 참고: OSIV가 활성화된 경우 개발자는 플러시를 방지하기 위해 트랜잭션 외부에서 이 작업을 수행하는 한 가져오지 않은 지연 연결을 수동으로 초기화할 수 있습니다. 그런데 이것이 왜 작동하는 걸까요? Session
이 열려 있는데 관리되는 엔터티의 연결을 수동으로 초기화해도 플러시가 트리거되지 않는 이유는 무엇입니까? 대답은 다음을 지정하는 OpenSessionInViewFilter
의 문서에서 찾을 수 있습니다. 이 필터는 기본적으로 플러시 모드가 FlushMode.NEVER
로 설정된 Hibernate Session
을 플러시하지 않습니다. 플러시를 관리하는 서비스 계층 트랜잭션과 함께 사용되는 것으로 가정합니다. 활성 트랜잭션 관리자는 읽기-쓰기 트랜잭션 중에 플러시 모드를 일시적으로 FlushMode.AUTO
로 변경하고 마지막에는 플러시 모드를 FlushMode.NEVER
로 재설정합니다. 각 거래의. 트랜잭션 없이 이 필터를 사용하려면 기본 플러시 모드를 변경하는 것이 좋습니다("flushMode" 속성을 통해).
설명: 이 애플리케이션은 JPQL 및 기본 SQL(MySQL용)을 통해 작성된 Spring Projections(DTO) 및 내부 조인을 사용하기 위한 개념 증명입니다.
핵심 사항:
@OneToMany
연결의 Author
및 Book
)resources/data-mysql.sql
파일 확인).AuthorNameBookTitle.java
확인)설명: 이 애플리케이션은 JPQL 및 기본 SQL(MySQL용)을 통해 작성된 Spring Projections(DTO) 및 Left Join을 사용하기 위한 개념 증명입니다.
핵심 사항:
@OneToMany
연결의 Author
및 Book
)resources/data-mysql.sql
파일 확인).AuthorNameBookTitle.java
확인).설명 : 이 응용 프로그램은 Spring Projection (DTO)을 사용하기위한 개념 증명이며 JPQL 및 Native SQL (MySQL)을 통해 작성된 오른쪽 조인입니다.
핵심 사항:
@OneToMany
Association의 Author
및 Book
)resources/data-mysql.sql
확인하십시오).AuthorNameBookTitle.java
확인).설명 : 이 응용 프로그램은 Spring Projections (DTO)를 사용하고 JPQL 및 기본 SQL (PostgreSQL)을 통해 작성된 포괄적 인 전체 조인을 사용하기위한 개념 증명입니다.
핵심 사항:
@OneToMany
Association의 Author
및 Book
)resources/data-mysql.sql
확인하십시오).AuthorNameBookTitle.java
확인).이 저장소에 노출 된 성능 레시피에 대한 깊은 다이빙이 필요하다면 내 책 "Spring Boot Persistence 모범 사례"를 좋아할 것입니다. | 100 개 이상의 Java Persistence Performance 문제에 대한 팁과 삽화가 필요한 경우 "Java Persistence Performance Illustrated Guide"가 귀하를위한 것입니다. |
설명 : 이 응용 프로그램은 Spring Projection (DTO)을 사용하기위한 개념 증명이며 JPQL 및 Native SQL (MySQL)을 통해 작성된 독점 왼쪽 조인입니다.
핵심 사항:
@OneToMany
Association의 Author
및 Book
)resources/data-mysql.sql
확인하십시오).AuthorNameBookTitle.java
확인).설명 : 이 응용 프로그램은 Spring Projection (DTO)을 사용하기위한 개념 증명이며 JPQL 및 Native SQL (MySQL)을 통해 작성된 독점 오른쪽 조인입니다.
핵심 사항:
@OneToMany
Association의 Author
및 Book
)resources/data-mysql.sql
확인하십시오).AuthorNameBookTitle.java
확인).설명 : 이 응용 프로그램은 스프링 투영 (DTO)을 사용하기위한 개념 증명이며 JPQL 및 기본 SQL (PostgreSQL)을 통해 작성된 전용 전체 조인입니다.
핵심 사항:
@OneToMany
Association의 Author
및 Book
)resources/data-mysql.sql
확인하십시오).AuthorNameBookTitle.java
확인).설명 : 이 응용 프로그램은 스프링 포스트 커밋 후크를 사용하고 지속성 층 성능에 영향을 줄 수있는 개념 증명입니다.
핵심 사항:
설명 : 이 응용 프로그램은 Spring Projection (DTO)을 사용하고 관련없는 엔티티에 가입하기위한 개념 증명입니다. Hibernate 5.1은 관련없는 엔티티에 대한 명시 적 조인을 소개했으며 구문 및 동작은 SQL JOIN
문과 유사합니다.
핵심 사항:
Author
및 Book
관련이없는 엔티티)resources/data-mysql.sql
확인하십시오).BookstoreDto
)@EqualsAndHashCode
및 @Data
피하는 이유와 equals()
및 hashCode()
무시하는 방법 설명 : 엔티티는 여기와 같이 equals()
및 hashCode()
구현해야합니다. 주요 아이디어는 최대 절전 모드는 엔티티가 모든 상태 전환 ( 과도 , 부착 , 분리 및 제거 )에서 자체와 동일해야한다는 것입니다. lombok @EqualsAndHashCode
(또는 @Data
)를 사용해 도이 요구 사항을 존중하지 않습니다.
핵심 사항:
이러한 접근법을 피하십시오
@EqualsAndHashCode
의 Lombok 기본 동작 사용 (Entity : LombokDefaultBook
, Test : LombokDefaultEqualsAndHashCodeTest
)@EqualsAndHashCode
사용 (Entity : LombokIdBook
, Test : LombokEqualsAndHashCodeWithIdOnlyTest
)equals()
및 hashCode()
(엔티티 : DefaultBook
, Test : DefaultEqualsAndHashCodeTest
)에 의존합니다.equals()
및 hashCode()
에 의존합니다 (엔티티 : IdBook
, test : IdEqualsAndHashCodeTest
)이러한 접근법을 선호합니다
BusinessKeyBook
, Test : BusinessKeyEqualsAndHashCodeTest
)에 의존합니다.@NaturalId
에 의존합니다 (Entity : NaturalIdBook
, Test : NaturalIdEqualsAndHashCodeTest
)IdManBook
, Test : IdManEqualsAndHashCodeTest
)에 의존합니다.IdGenBook
, Test : IdGenEqualsAndHashCodeTest
)에 의존합니다. JOIN FETCH
통해 LazyInitializationException
피하는 방법참조:
설명 : 일반적으로 LazyInitializationException
을 얻을 때 우리는 연관 페치 유형을 LAZY
것에서 EAGER
수정하는 경향이 있습니다. 그것은 매우 나쁩니다! 이것은 코드 냄새입니다. 이 예외를 피하는 가장 좋은 방법은 JOIN FETCH
(Fetched Entities를 수정하려는 경우) 또는 + JOIN
(페치 된 데이터 만 읽는 경우)에 의존하는 것입니다. JOIN FETCH
단일 SELECT
사용하여 부모 객체와 함께 연결을 초기화 할 수 있습니다. 이것은 관련 컬렉션을 가져 오는 데 특히 유용합니다.
이 응용 프로그램은 LazyInitializationException
피하기위한 JOIN FETCH
예제입니다.
핵심 사항:
@OneToMany
Lazy-Bidirectional Association의 Author
및 Book
)JOIN FETCH
작성하여 그의 책을 포함한 저자를 가져 오기JOIN FETCH
(또는 JOIN
)를 작성하여 저자를 포함한 책을 가져 오십시오. 출력 예:
설명 : 이것은 다음 기사를 기반으로 한 스프링 부팅 예입니다. 블라드의 예제의 기능적 구현입니다. 해당 기사를 읽는 것이 좋습니다.
핵심 사항:
설명 : 이것은 필요에 따라 연결 획득을 지연시키는 5.2.10 기능을 이용하는 스프링 부팅 예입니다. 기본적으로 리소스-로컬 모드에서 @Transactional
과 주석이 달린 메소드를 호출 한 후 즉시 데이터베이스 연결이 Aquried됩니다. 이 메소드에 첫 번째 SQL 문 앞에 시간이 많이 걸리는 작업이 포함되어 있으면 연결은 아무것도 열리지 않습니다. 그러나 Hibernate 5.2.10을 사용하면 필요에 따라 연결 획득을 지연시킬 수 있습니다. 이 예제는 Spring Boot의 기본 연결 풀로 Hikaricp에 의존합니다.
핵심 사항:
spring.datasource.hikari.auto-commit=false
설정합니다spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true
application.properties
에서 true를 설정합니다 출력 예:
hi/lo
알고리즘을 통해 식별자 시퀀스를 생성하는 방법 참고 : 애플리케이션 외부의 시스템이 테이블에 행을 삽입 해야하는 경우 hi/lo
알고리즘에 의존하지 않으면이 경우 복제 된 식별자를 생성하여 오류가 발생할 수 있습니다. pooled
또는 pooled-lo
알고리즘 ( hi/lo
의 최적화)에 의존하십시오.
설명 : 이것은 30 개의 배치로 1000 인서트를 배치하기 위해 10 개의 데이터베이스 라운드에서 1000 개의 식별자를 생성하기 위해 hi/lo
알고리즘을 사용하는 스프링 부팅 예입니다.
핵심 사항:
SEQUENCE
생성기 유형을 사용하십시오 (예 : PostgreSQL에서)Author.java
엔티티에서와 같이 hi/lo
알고리즘을 구성하십시오 출력 예:
이 저장소에 노출 된 성능 레시피에 대한 깊은 다이빙이 필요하다면 내 책 "Spring Boot Persistence 모범 사례"를 좋아할 것입니다. | 100 개 이상의 Java Persistence Performance 문제에 대한 팁과 삽화가 필요한 경우 "Java Persistence Performance Illustrated Guide"가 귀하를위한 것입니다. |
@ManyToMany
협회를 구현하는 가장 좋은 방법 설명 : 이 응용 프로그램은 성능 관점에서 양방향 @ManyToMany
연관을 구현하는 것이 어떻게 올바른지에 대한 개념 증명입니다.
핵심 사항:
mappedBy
쪽을 선택하십시오Set
아닌 List
통해 관계 컬렉션을 실현하십시오CascadeType.PERSIST
및 CascadeType.MERGE
사용하지만 CascadeType.REMOVE/ALL
피하십시오.@ManyToMany
는 기본적으로 게으르다. 이렇게 유지하십시오!@NaturalId
)) 및/또는 데이터베이스 생성 식별자를 사용하고 여기에서와 같이 equals()
및 hashCode()
메소드를 올바르게 재정의합니다.toString()
재정의 해야하는 경우 엔티티가 데이터베이스에서로드 될 때 가져온 기본 속성에 대해서만주의를 기울여야합니다.@ManyToMany
Associations에서 List
대신 Set
선호합니다 설명 : 이것은 각각 List
Set
사용하여 양방향 @ManyToMany
의 경우 행을 제거하는 스프링 부팅 예입니다. 결론은 Set
훨씬 더 좋다는 것입니다! 이것은 단방향에도 적용됩니다!
핵심 사항:
Set
사용하는 것은 List
보다 훨씬 효율적입니다 출력 예:
log4jdbc
통해 쿼리 세부 정보를 보는 방법설명 : log4jdbc를 통해 쿼리 세부 정보를보십시오.
핵심 사항:
pom.xml
에서 maven의 경우 log4jdbc
종속성을 추가하십시오 출력 샘플 :
설명 : TRACE
통해 준비된 명령문 바인딩/추출 매개 변수를 봅니다.
핵심 사항:
application.properties
에서 추가 : logging.level.org.hibernate.type.descriptor.sql=TRACE
출력 샘플 :
java.time.YearMonth
저장하는 방법 Hibernate Type Library를 통한 Integer
또는 Date
설명 : 최대 절전 모드 유형은 최대 절전 모드 코어에서 기본적으로 지원되지 않는 추가 유형 세트입니다. 이러한 유형 중 하나는 java.time.YearMonth
입니다. 이것은 최대 절전 모드 유형을 사용하여 YearMonth
MySQL 데이터베이스에 정수 또는 날짜로 저장하는 스프링 부트 응용 프로그램입니다.
핵심 사항:
pom.xml
의 종속성으로 최대 절전 모드 유형을 추가하십시오.@TypeDef
사용하여 typeClass
defaultForType
에 매핑하십시오 출력 예:
참고 : JPA 2.1의 쿼리의 WHERE
부분 ( SELECT
부분이 아님)에서 SQL 함수를 사용하면 여기에서와 같이 function()
통해 수행 할 수 있습니다.
설명 : JPQL 쿼리에서 SQL 함수 (표준 또는 정의)를 사용하려고하면 Hibernate가 인식하지 못하고 JPQL 쿼리를 구문 분석 할 수없는 경우 예외가 발생할 수 있습니다. 예를 들어, MySQL, concat_ws
함수는 최대 절전 모드로 인식되지 않습니다. 이 응용 프로그램은 MetadataBuilderContributor
통해 concat_ws
기능을 등록하고 metadata_builder_contributor
속성을 통해 Hibernate에게 알리는 Hibernate 5.3을 기반으로하는 Spring Boot 응용 프로그램입니다. 이 예제는 @Query
및 EntityManager
도 사용하므로 두 가지 사용 사례를 볼 수 있습니다.
핵심 사항:
MetadataBuilderContributor
구현하고 concat_ws
mysql 함수를 등록하십시오application.properties
에서 spring.jpa.properties.hibernate.metadata_builder_contributor
설정하여 MetadataBuilderContributor
구현의 최대 요선을 지적합니다. 출력 예:
설명 : 이 응용 프로그램은 DataSource-Proxy를 통한 느린 쿼리 만 기록하는 샘플입니다. 느린 쿼리는 실행 시간이 밀리 초의 특정 임계 값보다 큰 쿼리입니다.
핵심 사항:
pom.xml
에 데이터 소스-프로스-록시 의존성을 추가하십시오DataSource
Bean을 가로 채기 위해 Bean Post 프로세서 작성ProxyFactory
및 MethodInterceptor
구현을 통해 DataSource
Bean을 랩핑하십시오.afterQuery()
재정의합니다. 출력 예:
Page<dto>
SELECT COUNT
. 설명 : 이 응용 프로그램은 스프링 부팅 오프셋 페이지 매김을 통해 데이터를 Page<dto>
로 가져옵니다. 대부분의 경우, 페이지를 입은 데이터는 읽기 전용 데이터입니다. 데이터를 엔티티로 가져 오는 것은 해당 데이터를 수정하려는 경우에만 수행되어야하므로 Page<entity>
로 전용 데이터를 가져 오는 것이 상당한 성능 페널티가 될 수 있으므로 바람직하지 않습니다. 총 레코드 수를 계산하기 위해 트리거 된 SELECT COUNT
기본 SELECT
의 하위 쿼리입니다. 따라서 두 개 대신 단일 데이터베이스 라운드 트립이 있습니다 (일반적으로 데이터를 가져 오는 데 필요한 쿼리가 하나 있고 총 레코드 수를 계산하는 데 하나).
핵심 사항:
PagingAndSortingRepository
확장하는 저장소를 작성하십시오List<dto>
으로 가져옵니다.List<dto>
와 적절한 Pageable
사용하여 Page<dto>
만듭니다.List<dto>
SELECT COUNT
. 설명 : 이 응용 프로그램은 스프링 부팅 오프셋 페이지 매김을 통해 데이터를 List<dto>
으로 가져옵니다. 대부분의 경우, 페이지를 입은 데이터는 읽기 전용 데이터입니다. 데이터를 엔티티로 가져 오는 것은 해당 데이터를 수정하려는 경우에만 수행되어야하므로, 읽기 전용 데이터를 List<entity>
로 가져 오는 것이 상당한 성능 페널티가 될 수 있으므로 바람직하지 않습니다. 총 레코드 수를 계산하기 위해 트리거 된 SELECT COUNT
기본 SELECT
의 하위 쿼리입니다. 따라서 두 개 대신 단일 데이터베이스 라운드 트립이 있습니다 (일반적으로 데이터를 가져 오는 데 필요한 쿼리가 하나 있고 총 레코드 수를 계산하는 데 하나).
핵심 사항:
PagingAndSortingRepository
확장하는 저장소를 작성하십시오List<dto>
으로 가져옵니다. spring-boot-starter-jdbc
또는 spring-boot-starter-data-jpa
"Starters"를 사용하는 경우 Hikaricp에 자동으로 종속성을 얻습니다.
참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 application.properties
를 통해 hikaricp를 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다. 연결 풀 상태를 공개하는 Hickaricp 보고서를 확인하십시오.
핵심 사항:
application.properties
에서 spring.datasource.hikari.*
에 의존하여 Hikaricp를 구성하십시오 출력 샘플 :
이 저장소에 노출 된 성능 레시피에 대한 깊은 다이빙이 필요하다면 내 책 "Spring Boot Persistence 모범 사례"를 좋아할 것입니다. | 100 개 이상의 Java Persistence Performance 문제에 대한 팁과 삽화가 필요한 경우 "Java Persistence Performance Illustrated Guide"가 귀하를위한 것입니다. |
DataSourceBuilder
통해 Hikaricp 설정을 사용자 정의하는 방법 spring-boot-starter-jdbc
또는 spring-boot-starter-data-jpa
"Starters"를 사용하는 경우 Hikaricp에 자동으로 종속성을 얻습니다.
참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 hikaricp를 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다. 연결 풀 상태를 공개하는 Hickaricp 보고서를 확인하십시오.
핵심 사항:
application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오 출력 샘플 :
이 응용 프로그램은이 Dzone 기사에 자세히 설명되어 있습니다.
DataSourceBuilder
통해 Bonecp 설정을 사용자 정의하는 방법참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 Bonecp를 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다.
핵심 사항:
pom.xml
에서 Bonecp 종속성을 추가하십시오application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오 출력 샘플 :
DataSourceBuilder
통해 ViburdBCP 설정을 사용자 정의하는 방법참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 ViburdBCP를 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다.
핵심 사항:
pom.xml
에서 viburdbcp 종속성을 추가하십시오application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오 출력 샘플 :
DataSourceBuilder
통해 C3P0 설정을 사용자 정의하는 방법참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 C3P0을 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다.
핵심 사항:
pom.xml
에서 C3P0 종속성을 추가하십시오application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오 출력 샘플 :
DataSourceBuilder
통해 DBCP2 설정을 사용자 정의하는 방법참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 DBCP2를 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다.
핵심 사항:
pom.xml
에서 dbcp2 종속성을 추가하십시오application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오DataSourceBuilder
통해 Tomcat 설정을 사용자 정의하는 방법참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 DataSourceBuilder
통해 Tomcat을 설정하는 킥오프 응용 프로그램입니다. jdbcUrl
MySQL 데이터베이스 용으로 설정됩니다. 테스트 목적으로 응용 프로그램은 동시 사용자를 시뮬레이션하기 위해 ExecutorService
사용합니다.
핵심 사항:
pom.xml
에서 Tomcat 의존성을 추가하십시오application.properties
에서 사용자 정의 접두사 (예 : app.datasource.*
DataSource
반환하는 @Bean
을 작성하십시오 출력 샘플 :
참고 : Connection Pool 매개 변수를 조정하는 가장 좋은 방법은 Vlad Mihalcea의 Flexy Pool을 사용하는 것으로 구성됩니다. Flexy Pool을 통해 연결 풀의 고성능을 유지하는 최적 설정을 찾을 수 있습니다.
설명 : 이것은 두 개의 데이터 소스 (2 개의 MySQL 데이터베이스, 하나는 jororsDB라는 이름의 authorsdb
및 1 개의 이름이 지정된 booksdb
)를 사용하는 킥오프 응용 프로그램입니다 (각 데이터베이스는 다른 설정이있는 자체 HikarICP 연결 풀을 사용합니다). 위의 항목을 기반으로 한 두 개의 다른 제공 업체의 두 개의 연결 풀을 쉽게 구성하기 쉽습니다.
핵심 사항:
application.properties
에서는 두 개의 사용자 정의 접두사 (예 : app.datasource.ds1
및 app.datasource.ds2
통해 두 개의 Hikaricp 연결 풀을 구성하십시오.DataSource
반환하는 @Bean
작성하여 @Primary
로 표시하십시오.DataSource
반환하는 다른 @Bean
작성하십시오EntityManagerFactory
구성하고 각각을 스캔 할 패키지를 가리키십시오.EntityManager
의 도메인 및 저장소를 오른쪽 패키지에 넣으십시오. 출력 샘플 :
참고 : 세터를 변경하지 않고 유창한 API를 제공하려면이 항목을 고려하십시오.
설명 : 이것은 유창한 API를 강화하기 위해 엔티티 세터 메서드를 변경하는 샘플 응용 프로그램입니다.
핵심 사항:
void
대신 this
반환하십시오 유창한 API 예 :
참고 : 세터를 변경하여 유창한 API를 제공하려면이 항목을 고려하십시오.
설명 : 유창한 API에 권한을 부여하기 위해 엔티티 추가 방법 (예 : setName
의 경우 name
추가) 메소드를 추가하는 샘플 응용 프로그램입니다.
핵심 사항:
void
대신 this
반환하는 추가 메소드를 추가하십시오. 유창한 API 예 :
이 저장소에 노출 된 성능 레시피에 대한 깊은 다이빙이 필요하다면 내 책 "Spring Boot Persistence 모범 사례"를 좋아할 것입니다. | 100 개 이상의 Java Persistence Performance 문제에 대한 팁과 삽화가 필요한 경우 "Java Persistence Performance Illustrated Guide"가 귀하를위한 것입니다. |
Slice<T> findAll()
아마도 아마도 이것이 당신이 원하는 전부 일 것입니다 : Slice<entity>
/ Slice<dto>
fetchAll
/ fetchAllDto
통해 가져 오는 방법
Slice<T> findAll()
의 일부 구현 :
"SELECT e FROM " + entityClass.getSimpleName() + " e;"
CriteriaBuilder
기반으로 한 또 다른 미니멀리스트 구현입니다.Sort
을 제공 할 수있는 구현이므로 결과를 정렬 할 수 있습니다.Sort
및 스프링 데이터 Specification
제공 할 수있는 구현입니다.Sort
, LockModeType
, QueryHints
및 스프링 데이터 Specification
제공 할 수있는 구현입니다.Pageable
SimpleJpaRepository
스프링 데이터에서 확장하여 스프링 데이터 및/또는 Specification
제공 할 수있는 구현입니다. 기본적 으로이 구현은 Slice<T>
대신 Page<T>
반환하는 유일한 구현이지만 Page<T> readPage(...)
메소드를 재정의하여 제거되어 추가 SELECT COUNT
트리거하지 않습니다. SimpleJpaRepository
. 주요 단점은 Page<T>
유지함으로써 다음 페이지가 있는지 또는 현재 페이지가 마지막 페이지인지 알지 못한다는 것입니다. 그럼에도 불구하고, 이것을 갖는 해결 방법도 있습니다. 이 구현에서는 LockModeType
또는 쿼리 힌트를 설정할 수 없습니다. 스토리 : Spring Boot는 Page
또는 Slice
반환하는 오프셋 기반 내장 페이징 메커니즘을 제공합니다. 이러한 각 API는 데이터 페이지와 일부 메타 데이터를 나타냅니다. 주요 차이점은 Page
에 총 레코드 수가 포함되어 있고 Slice
사용 가능한 다른 페이지가 있는지 만 알 수 있다는 것입니다. Page
의 경우 Spring Boot는 인수로서 Pageable
및/또는 Specification
또는 Example
사용할 수있는 findAll()
메소드를 제공합니다. 총 레코드 수가 포함 된 Page
만들기 위해이 메소드는 현재 페이지의 데이터를 가져 오는 데 사용되는 쿼리 옆에 SELECT COUNT
추가 쿼리를 트리거합니다. 페이지를 요청할 때마다 SELECT COUNT
쿼리가 트리거되므로 성능 페널티가 될 수 있습니다. 이 여분의 쿼리를 피하기 위해 Spring Boot는보다 편안한 API 인 Slice
API를 제공합니다. Page
대신 Slice
사용하면이 추가 SELECT COUNT
쿼리의 필요성이 제거되고 총 레코드 수없이 페이지 (레코드) 및 일부 메타 데이터를 반환합니다. 따라서 Slice
총 레코드 수를 알지 못하지만 현재 페이지 또는이 페이지 후에 다른 페이지가 있는지 여부를 알 수 있습니다. 문제는 Slice
SQL WHERE
포함 된 쿼리 (스프링 데이터에 내장 된 쿼리 빌더 메커니즘을 사용하는 것)를 포함하는 쿼리에 대해 잘 작동하지만 findAll()
에서는 작동하지 않습니다 . 이 메소드는 여전히 Slice
대신 Page
반환하므로 SELECT COUNT
Query가 Slice<T> findAll(...);
.
설명 : 이것은 다양한 버전의 Slice<T> findAll(...)
메소드를 제공하는 샘플 애플리케이션 제품군입니다. "SELECT e FROM " + entityClass.getSimpleName() + " e";
(이 SimpleJpaRepository
), 정렬, 사양, 잠금 모드 및 쿼리 힌트를 지원하는 사용자 정의 구현.
핵심 사항:
Slice<T> findAll(...)
메소드를 노출 SlicePagingRepositoryImplementation
abstract
클래스 작성findAll()
메소드를 구현하여 Slice<T>
(또는 Page<T>
반환하지만 총 요소 수는 없음)SliceImpl
( Slice<T>
) 또는 PageImpl
( Page<T>
)을 반환합니다.readSlice()
메소드를 구현하거나 SimpleJpaRepository#readPage()
페이지를 재정의하여 SELECT COUNT
피하십시오.Author.class
)를이 abstract
클래스로 전달하십시오 ( AuthorRepository
)COUNT(*) OVER
및 리턴 List<dto>
설명 : 일반적으로 오프셋 페이지 매김에는 데이터를 가져 오는 데 필요한 쿼리가 하나 있고 총 레코드 수를 계산하는 데 하나가 있습니다. 그러나이 정보를 기본 SELECT
에 중첩 된 SELECT COUNT
하위 쿼리를 통해 단일 데이터베이스 Rountrip 에서이 정보를 가져올 수 있습니다. 더 좋은 점은 창 함수를 지원하는 데이터베이스 공급 업체 SELECT COUNT
경우이 응용 프로그램에서 MySQL 8에 대한 기본 쿼리 에서이 창 함수를 사용하는 COUNT(*) OVER()
에 의존하는 솔루션이 있습니다. .
핵심 사항:
COUNT(*) OVER()
예:
설명 : 오프셋 페이징에 의존 할 때 원하는 오프셋에 도달하기 전에 N 레코드를 버려 성능 페널티가 유발됩니다. 더 큰 N은 상당한 성과 페널티로 이어집니다. 우리가 큰 n을 가지고있을 때, 큰 데이터 세트의 "일정한"시간을 유지하는 Keyset Pagination에 의존하는 것이 좋습니다. 나쁜 오프셋이 어떻게 수행 할 수 있는지 이해하려면이 기사를 확인하십시오.
해당 기사의 스크린 샷 ( 오프셋 페이지 매김) :
더 많은 기록이 있는지 알아야합니까?
본질적으로 Keyset은 SELECT COUNT
사용하여 총 레코드 수를 가져 오지 않습니다. 그러나 약간의 조정으로 더 많은 레코드가 있는지 쉽게 말할 수 있으므로 Next Page
유형의 버튼을 표시 할 수 있습니다. 주로 그러한 것이 필요한 경우 다음은 다음과 같은 클라이맥스가있는이 응용 프로그램을 고려하십시오.
public AuthorView fetchNextPage(long id, int limit) {
List<Author> authors = authorRepository.fetchAll(id, limit + 1);
if (authors.size() == (limit + 1)) {
authors.remove(authors.size() - 1);
return new AuthorView(authors, true);
}
return new AuthorView(authors, false);
}
또는 이와 같이 ( Author.toString()
메소드에 의존) :
public Map<List<Author>, Boolean> fetchNextPage(long id, int limit) {
List<Author> authors = authorRepository.fetchAll(id, limit + 1);
if(authors.size() == (limit + 1)) {
authors.remove(authors.size() -1);
return Collections.singletonMap(authors, true);
}
return Collections.singletonMap(authors, false);
}
Previous Page
버튼은 첫 번째 레코드를 기반으로 쉽게 구현할 수 있습니다.
핵심 사항:
id
) 역할을하려면 열을 선택하십시오.WHERE
and ORDER BY
열을 사용하십시오.설명 : 이것은 클래식 스프링 부트 오프셋 페이지 매김 예입니다. 그러나 성능 페널티가 더 설명되어 있기 때문에이 접근법을 생산에 사용하는 것이 좋지 않습니다.
우리가 오프셋 페이지 매김에 의존 할 때, 우리는 원하는 오프셋에 도달하기 전에 N 레코드를 버려 성능 페널티를 유발합니다. 더 큰 N은 상당한 성과 페널티로 이어집니다. 또 다른 형벌은 총 레코드 수를 계산하는 데 필요한 추가 SELECT
입니다. 오프셋 Pagination이 어떻게 수행 할 수 있는지 이해하려면이 기사를 확인하십시오. 해당 기사의 스크린 샷은 다음과 같습니다. 그럼에도 불구하고 아마도이 예는 약간 극단적 일 것입니다. 상대적으로 작은 데이터 세트의 경우 오프셋 페이지 매김이 그렇게 나쁘지 않습니다 ( 키 세트 페이지 매김에 성능이 가깝습니다). Spring Boot는 Page
API를 통한 오프셋 페이지 매김에 대한 내장 지원을 제공하기 때문에 사용하기가 매우 쉽습니다. 그러나 사례에 따라 다음 예제에서와 같이 오프셋 페이지 매김을 약간 최적화 할 수 있습니다.
페이지를 Page
로 가져 오기 :
COUNT(*) OVER
및 반환 Page<dto>
COUNT(*) OVER
통해 Page<entity>
반환합니다Page<dto>
SELECT COUNT
Page<entity>
추가 열을 통해 SELECT COUNT
.Page<projection>
이 엔티티 및 투영을 통한 총 레코드 수를 SELECT COUNT
. 페이지를 List
으로 가져 오기 :
COUNT(*) OVER
및 리턴 List<dto>
COUNT(*) OVER
통해 List<entity>
반환합니다List<dto>
SELECT COUNT
List<entity>
SELECT COUNT
.List<projection>
이 엔티티 및 투영을 통한 총 레코드 수를 SELECT COUNT
.그러나 : 오프셋 페이지 매김이 성능 문제를 일으키고 Keyset Pagination을 사용하기로 결정한 경우 여기에서 확인하십시오 ( Keyset Pagination).
클래식 오프셋 페이지 매김의 핵심 사항 :
PagingAndSortingRepository
확장하는 저장소를 작성하십시오Page<entity>
고전적인 오프셋 페이지 매김의 예 :
findAll(Pageable)
호출하십시오.repository.findAll(PageRequest.of(page, size));
findAll(Pageable)
호출하십시오.repository.findAll(PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "name")));
Page<Author> findByName(String name, Pageable pageable);
Page<Author> queryFirst10ByName(String name, Pageable pageable);
설명 : Author
와 Book
단체 사이에 일대일 관계가 있다고 가정 해 봅시다. 우리가 저자를 구할 때, 우리는 Cascading All/Persist 덕분에 그의 책을 저장합니다. 우리는 책이있는 많은 저자를 만들고 배치 기술을 사용하여 데이터베이스 (예 : MySQL 데이터베이스)에 저장하려고합니다. 기본적으로, 이로 인해 각 저자와 저자 당 책을 배치 할 수 있습니다 (저자의 한 배치 및 책의 한 배치, 저자를위한 다른 배치 및 책의 다른 배치 등). In order to batch authors and books, we need to order inserts as in this application.
Key points: Beside all setting specific to batching inserts in MySQL, we need to set up in application.properties
the following property: spring.jpa.properties.hibernate.order_inserts=true
Example without ordered inserts:
Example with ordered inserts:
Implementations:
Description: Batch updates in MySQL.
핵심 사항:
application.properties
set spring.jpa.properties.hibernate.jdbc.batch_size
application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL, statements get rewritten into a single string buffer and sent in a single request)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))spring.jpa.properties.hibernate.order_updates=true
to optimize the batching by ordering 업데이트application.properties
a setting for enabling batching for versioned entities during update and delete operations (entities that contains @Version
for implicit optimistic locking); this setting is: spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true
; starting with Hibernate 5, this setting should be true
by defaultOutput example for single entity:
Output example for parent-child relationship:
Description: Batch deletes that don't involve associations in MySQL.
Note: Spring deleteAllInBatch()
and deleteInBatch()
don't use delete batching and don't take advantage of automatic optimstic locking mechanism to prevent lost updates (eg, @Version
is ignored). They rely on Query.executeUpdate()
to trigger bulk operations. These operations are fast, but Hibernate doesn't know which entities are removed, therefore, the Persistence Context is not updated accordingly (it's up to you to flush (before delete) and close/clear (after delete) the Persistence Context accordingly to avoid issues created by unflushed (if any) or outdated (if any) entities). The first one ( deleteAllInBatch()
) simply triggers a delete from entity_name
statement and is very useful for deleting all records. The second one ( deleteInBatch()
) triggers a delete from entity_name where id=? or id=? or id=? ...
statement, therefore, is prone to cause issues if the generated DELETE
statement exceedes the maximum accepted size. This issue can be controlled by deleting the data in chunks, relying on IN
operator, and so on. Bulk operations are faster than batching which can be achieved via the deleteAll()
, deleteAll(Iterable<? extends T> entities)
or delete()
method. Behind the scene, the two flavors of deleteAll()
relies on delete()
. The delete()
/ deleteAll()
methods rely on EntityManager.remove()
therefore the Persistence Context is synchronized accordingly. Moreover, if automatic optimstic locking mechanism (to prevent lost updates ) is enabled then it will be used.
Key points for regular delete batching:
deleteAll()
, deleteAll(Iterable<? extends T> entities)
or delete()
methodapplication.properties
set spring.jpa.properties.hibernate.jdbc.batch_size
application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL, statements get rewritten into a single string buffer and sent in a single request)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))application.properties
a setting for enabling batching for versioned entities during update and delete operations (entities that contains @Version
for implicit optimistic locking); this setting is: spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true
; starting with Hibernate 5, this setting should be true
by default 출력 예:
Description: Batch deletes in MySQL via orphanRemoval=true
.
Note: Spring deleteAllInBatch()
and deleteInBatch()
don't use delete batching and don't take advantage of cascading removal, orphanRemoval
and automatic optimstic locking mechanism to prevent lost updates (eg, @Version
is ignored). They rely on Query.executeUpdate()
to trigger bulk operations. These operations are fast, but Hibernate doesn't know which entities are removed, therefore, the Persistence Context is not updated accordingly (it's up to you to flush (before delete) and close/clear (after delete) the Persistence Context accordingly to avoid issues created by unflushed (if any) or outdated (if any) entities). The first one ( deleteAllInBatch()
) simply triggers a delete from entity_name
statement and is very useful for deleting all records. The second one ( deleteInBatch()
) triggers a delete from entity_name where id=? or id=? or id=? ...
statement, therefore, is prone to cause issues if the generated DELETE
statement exceedes the maximum accepted size. This issue can be controlled by deleting the data in chunks, relying on IN
operator, and so on. Bulk operations are faster than batching which can be achieved via the deleteAll()
, deleteAll(Iterable<? extends T> entities)
or delete()
method. Behind the scene, the two flavors of deleteAll()
relies on delete()
. The delete()
/ deleteAll()
methods rely on EntityManager.remove()
therefore the Persistence Context is synchronized accordingly. If automatic optimstic locking mechanism (to prevent lost updates ) is enabled then it will be used. Moreover, cascading removals and orphanRemoval
works as well.
Key points for using deleteAll()/delete()
:
Author
entity and each author can have several Book
( one-to-many )orphanRemoval=true
and CascadeType.ALL
Book
from the corresponding Author
orphanRemoval=true
to enter into the scene; thanks to this setting, all disassociated books will be deleted; the generated DELETE
statements are batched (if orphanRemoval
is set to false
, a bunch of updates will be executed instead of deletes)Author
via the deleteAll()
or delete()
method (since we have dissaciated all Book
, the Author
deletion will take advantage of batching as well)ON DELETE CASCADE
Description: Batch deletes in MySQL via ON DELETE CASCADE
. Auto-generated database schema will contain the ON DELETE CASCADE
directive.
Note: Spring deleteAllInBatch()
and deleteInBatch()
don't use delete batching and don't take advantage of cascading removal, orphanRemoval
and automatic optimistic locking mechanism to prevent lost updates (eg, @Version
is ignored), but both of them take advantage on ON DELETE CASCADE
and are very efficient. They trigger bulk operations via Query.executeUpdate()
, therefore, the Persistence Context is not synchronized accordingly (it's up to you to flush (before delete) and close/clear (after delete) the Persistence Context accordingly to avoid issues created by unflushed (if any) or outdated (if any) entities). The first one simply triggers a delete from entity_name
statement, while the second one triggers a delete from entity_name where id=? or id=? or id=? ...
성명. For delete in batches rely on deleteAll()
, deleteAll(Iterable<? extends T> entities)
or delete()
method. Behind the scene, the two flavors of deleteAll()
relies on delete()
. Mixing batching with database automatic actions ( ON DELETE CASCADE
) will result in a partially synchronized Persistent Context.
핵심 사항:
Author
entity and each author can have several Book
( one-to-many )orphanRemoval
or set it to false
CascadeType.PERSIST
and CascadeType.MERGE
@OnDelete(action = OnDeleteAction.CASCADE)
next to @OneToMany
spring.jpa.properties.hibernate.dialect
to org.hibernate.dialect.MySQL5InnoDBDialect
(or, MySQL8Dialect
)deleteFoo()
methods that uses bulk and batching deletes as well출력 예:
@NaturalId
In Spring Boot Style Alternative implementation: In case that you want to avoid extending SimpleJpaRepository
check this implementation.
Description: This is a SpringBoot application that maps a natural business key using Hibernate @NaturalId
. This implementation allows us to use @NaturalId
as it was provided by Spring.
핵심 사항:
Book
), mark the properties (business keys) that should act as natural IDs with @NaturalId
; commonly, there is a single such property, but multiple are suppored as well as here@NaturalId(mutable = false)
and @Column(nullable = false, updatable = false, unique = true, ...)
@NaturalId(mutable = true)
and @Column(nullable = false, updatable = true, unique = true, ...)
equals()
and hashCode()
using the natural id(s)@NoRepositoryBean
interface ( NaturalRepository
) to define two methods, named findBySimpleNaturalId()
and findByNaturalId()
NaturalRepositoryImpl
) relying on Hibernate, Session
, bySimpleNaturalId()
and byNaturalId()
methods@EnableJpaRepositories(repositoryBaseClass = NaturalRepositoryImpl.class)
to register this implementation as the base classfindBySimpleNaturalId()
or findByNaturalId()
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Description: This is a Spring Boot application that uses P6Spy. P6Spy is a framework that enables database data to be seamlessly intercepted and logged with no code changes to the application.
핵심 사항:
pom.xml
, add the P6Spy Maven dependencyapplication.properties
, set up JDBC URL as, jdbc:p6spy:mysql://localhost:3306/db_users
application.properties
, set up driver class name as, com.p6spy.engine.spy.P6SpyDriver
spy.properties
(this file contains P6Spy configurations); in this application, the logs will be outputed to console, but you can easy switch to a file; more details about P6Spy configurations can be found in documentation Output sample:
OptimisticLockException
Exception ( @Version
) Note: Optimistic locking mechanism via @Version
works for detached entities as well.
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception. When such exception occur, the application retry the corresponding transaction via db-util library developed by Vlad Mihalcea.
핵심 사항:
pom.xml
, add the db-util
dependencyOptimisticConcurrencyControlAspect
bean@Transactional
) that is prone to throw (or that calls a method that is prone to throw (this method can be annotated with @Transactional
)) an optimistic locking exception with @Retry(times = 10, on = OptimisticLockingFailureException.class)
Output sample:
OptimisticLockException
Exception (Hibernate Version-less Optimistic Locking Mechanism)Note: Optimistic locking mechanism via Hibernate version-less doesn't work for detached entities (don't close the Persistent Context).
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception (eg, in Spring Boot, OptimisticLockingFailureException
) via Hibernate version-less optimistic locking. When such exception occur, the application retry the corresponding transaction via db-util library developed by Vlad Mihalcea.
핵심 사항:
pom.xml
, add the db-util
library dependencyOptimisticConcurrencyControlAspect
beanInventory
) with @DynamicUpdate
and @OptimisticLocking(type = OptimisticLockType.DIRTY)
@Transactional
) that is prone to throw (or that calls a method that is prone to throw (this method can be annotated with @Transactional
)) an optimistic locking exception with @Retry(times = 10, on = OptimisticLockingFailureException.class)
Note: You may also like to read the recipe, "How To Create DTO Via Spring Data Projections"
Description: This is an application sample that fetches only the needed columns from the database via Spring Data Projections (DTO) and enrich the result via virtual properties.
핵심 사항:
name
and age
AuthorNameAge
, use the @Value
and Spring SpEL to point to a backing property from the domain model (in this case, the domain model property age
is exposed via the virtual property years
)AuthorNameAge
, use the @Value
and Spring SpEL to enrich the result with two virtual properties that don't have a match in the domain model (in this case, rank
and books
) 출력 예:
Description: Spring Data comes with the query creation mechanism for JPA that is capable to interpret a query method name and convert it into a SQL query in the proper dialect. This is possible as long as we respect the naming conventions of this mechanism. This is an application that exploit this mechanism to write queries that limit the result size. Basically, the name of the query method instructs Spring Data how to add the LIMIT
(or similar clauses depending on the RDBMS) clause to the generated SQL queries.
핵심 사항:
AuthorRepository
) 예:
- List<Author> findFirst5ByAge(int age);
- List<Author> findFirst5ByAgeGreaterThanEqual(int age);
- List<Author> findFirst5ByAgeLessThan(int age);
- List<Author> findFirst5ByAgeOrderByNameDesc(int age);
- List<Author> findFirst5ByGenreOrderByAgeAsc(String genre);
- List<Author> findFirst5ByAgeGreaterThanEqualOrderByNameAsc(int age);
- List<Author> findFirst5ByGenreAndAgeLessThanOrderByNameDesc(String genre, int age);
- List<AuthorDto> findFirst5ByOrderByAgeAsc();
- Page<Author> queryFirst10ByName(String name, Pageable p);
- Slice<Author> findFirst10ByName(String name, Pageable p);
The list of supported keywords is listed below:
schema-*.sql
In MySQL Note: As a rule, in real applications avoid generating schema via hibernate.ddl-auto
or set it to validate
. Use schema-*.sql
file or better Flyway
or Liquibase
migration tools.
Description: This application is an example of using schema-*.sql
to generate a schema(database) in MySQL.
핵심 사항:
application.properties
, set the JDBC URL (eg, spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
)application.properties
, disable DDL auto (just don't add explicitly the hibernate.ddl-auto
setting)application.properties
, instruct Spring Boot to initialize the schema from schema-mysql.sql
fileschema-*.sql
And Match Entities To Them Via @Table
In MySQL Note: As a rule, in real applications avoid generating schema via hibernate.ddl-auto
or set it to validate
. Use schema-*.sql
file or better Flyway
or Liquibase
.
Description: This application is an example of using schema-*.sql
to generate two databases in MySQL. The databases are matched at entity mapping via @Table
.
핵심 사항:
application.properties
, set the JDBC URL without the database, eg, spring.datasource.url=jdbc:mysql://localhost:3306
application.properties
, disable DDL auto (just don't specify hibernate.ddl-auto
)aaplication.properties
, instruct Spring Boot to initialize the schema from schema-mysql.sql
fileAuthor
entity, specify that the corresponding table ( author
) is in the database authorsdb
via @Table(schema="authorsdb")
Book
entity, specify that the corresponding table ( book
) is in the database booksdb
via @Table(schema="booksdb")
출력 예:
Author
results in the following SQL: insert into authorsdb.author (age, genre, name) values (?, ?, ?)
Book
results the following SQL: insert into booksdb.book (isbn, title) values (?, ?)
Note: For web-applications, pagination should be the way to go, not streaming. But, if you choose streaming then keep in mind the golden rule: keep th result set as small as posible. Also, keep in mind that the Execution Plan might not be as efficient as when using SQL-level pagination.
Description: This application is an example of streaming the result set via Spring Data and MySQL. This example can be adopted for databases that fetches the entire result set in a single roundtrip causing performance penalties.
핵심 사항:
@Transactional(readOnly=true)
)Integer.MIN_VALUE
(recommended in MySQL))Statement
fetch-size to Integer.MIN_VALUE
, or add useCursorFetch=true
to the JDBC URL and set Statement
fetch-size to a positive integer (eg, 30)createDatabaseIfNotExist
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of migrating a MySQL database via Flyway when the database exists (it is created before migration via MySQL specific parameter, createDatabaseIfNotExist=true
).
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
application.properties
, set the JDBC URL as follows: jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true
classpath:db/migration
V1.1__Description.sql
, V1.2__Description.sql
, ...spring.flyway.schemas
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of migrating a MySQL database when the database is created by Flyway via spring.flyway.schemas
. In this case, the entities should be annotated with @Table(schema = "bookstoredb")
or @Table(catalog = "bookstoredb")
. Here, the database name is bookstoredb
.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
application.properties
, set the JDBC URL as follows: jdbc:mysql://localhost:3306/
application.properties
, add spring.flyway.schemas=bookstoredb
, where bookstoredb
is the database that should be created by Flyway (feel free to add your own database name)@Table(schema/catalog = "bookstoredb")
classpath:db/migration
V1.1__Description.sql
, V1.2__Description.sql
, ... Output of migration history example:
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Note: For production don't rely on hibernate.ddl-auto
to create your schema. Remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of auto-creating and migrating schemas for MySQL and PostgreSQL. In addition, each data source uses its own HikariCP connection pool. In case of MySQL, where schema = database , we auto-create the schema ( authorsdb
) based on createDatabaseIfNotExist=true
. In case of PostgreSQL, where a database can have multiple schemas, we use the default postgres
database and auto-create in it the schema, booksdb
. For this we rely on Flyway, which is capable to create a missing schema.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
application.properties
, configure the JDBC URL for MySQL as, jdbc:mysql://localhost:3306/authorsdb?createDatabaseIfNotExist=true
and for PostgreSQL as, jdbc:postgresql://localhost:5432/postgres?currentSchema=booksdb
application.properties
, set spring.flyway.enabled=false
to disable default behaviorDataSource
for MySQL and one for PostgreSQLFlywayDataSource
for MySQL and one for PostgreSQLEntityManagerFactory
for MySQL and one for PostgreSQLdbmigrationmysql
dbmigrationpostgresql
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of auto-creating and migrating two schemas in PostgreSQL using Flyway. In addition, each data source uses its own HikariCP connection pool. In case of PostgreSQL, where a database can have multiple schemas, we use the default postgres
database and auto-create two schemas, authors
and books
. For this we rely on Flyway, which is capable to create the missing schemas.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
application.properties
, configure the JDBC URL for books
as jdbc:postgresql://localhost:5432/postgres?currentSchema=books
and for authors
as jdbc:postgresql://localhost:5432/postgres?currentSchema=authors
application.properties
, set spring.flyway.enabled=false
to disable default behaviorDataSource
, one for books
and one for authors
FlywayDataSource
, one for books
and one for authors
EntityManagerFactory
, one for books
and one for authors
books
, place the migration SQLs files in dbmigrationbooks
authors
, place the migration SQLs files in dbmigrationauthors
JOIN FETCH
an @ElementCollection
Description: This application is an example applying JOIN FETCH
to fetch an @ElementCollection
.
핵심 사항:
@ElementCollection
is loaded lazy, keep it lazyJOIN FETCH
in the repository@Subselect
) in a Spring Boot Application Note: Consider using @Subselect
only if using DTO, DTO and extra queries, or map a database view to an entity is not a solution.
Description: This application is an example of mapping an entity to a query via Hibernate, @Subselect
. Mainly, we have two entities in a bidirectional one-to-many association. An Author
has wrote several Book
. The idea is to write a read-only query to fetch from Author
only some fields (eg, DTO), but to have the posibility to call getBooks()
and fetch the Book
in a lazy manner as well. As you know, a classic DTO cannot be used, since such DTO is not managed and we cannot navigate the associations (don't support any managed associations to other entities). Via Hibernate @Subselect
we can map a read-only and immutable entity to a query. This time, we can lazy navigate the associations.
핵심 사항:
Author
(including association to Book
)@Immutable
since no write operations are allowed@Synchronize
@Subselect
to write the needed query, map an entity to an SQL queryDescription: This application is an example of using Hibernate soft deletes in a Spring Boot application.
핵심 사항:
abstract
class BaseEntity
with a field named deleted
Author
and Book
entities) that should take advantage of soft deletes should extend BaseEntity
@Where
annotation like this: @Where(clause = "deleted = false")
@SQLDelete
annotation to trigger UPDATE
SQLs in place of DELETE
SQLs, as follows: @SQLDelete(sql = "UPDATE author SET deleted = true WHERE id = ?")
출력 예:
DataSourceBuilder
If you use the spring-boot-starter-jdbc
or spring-boot-starter-data-jpa
"starters", you automatically get a dependency to HikariCP
Note: The best way to tune the connection pool parameters consist in using Flexy Pool by Vlad Mihalcea. Via Flexy Pool you can find the optim settings that sustain high-performance of your connection pool.
Description: This is a kickoff application that set up HikariCP via DataSourceBuilder
. The jdbcUrl
is set up for a MySQL database. For testing purposes, the application uses an ExecutorService
for simulating concurrent users. Check the HickariCP report revealing the connection pool status.
핵심 사항:
@Bean
that returns the DataSource
programmaticallyDescription: Auditing is useful for maintaining history records. This can later help us in tracking user activities.
핵심 사항:
abstract
base entity (eg, BaseEntity
) and annotate it with @MappedSuperclass
and @EntityListeners({AuditingEntityListener.class})
@CreatedDate protected LocalDateTime created;
@LastModifiedDate protected LocalDateTime lastModified;
@CreatedBy protected U createdBy;
@LastModifiedBy protected U lastModifiedBy;
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
AuditorAware
(this is needed for persisting the user that performed the modification; use Spring Security to return the currently logged-in user)@Bean
spring.jpa.hibernate.ddl-auto=create
)Description: Auditing is useful for maintaining history records. This can later help us in tracking user activities.
핵심 사항:
@Audited
@AuditTable
to rename the table used for auditingValidityAuditStrategy
for fast database reads, but slower writes (slower than the default DefaultAuditStrategy
)Description: By default, the attributes of an entity are loaded eager (all at once). This application is an alternative to How To Use Hibernate Attribute Lazy Loading from here. This application uses a base class to isolate the attributes that should be loaded eagerly and subentities (entities that extends the base class) for isolating the attributes that should be loaded on demand.
핵심 사항:
BaseAuthor
, and annotate it with @MappedSuperclass
AuthorShallow
subentity of BaseAuthor
and don't add any attribute in it (this will inherit the attributes from the superclass)AuthorDeep
subentity of BaseAuthor
and add to it the attributes that should be loaded on demand (eg, avatar
)@Table(name = "author")
AuthorShallowRepository
and AuthorDeepRepository
Run the following requests (via BookstoreController):
localhost:8080/authors/shallow
localhost:8080/authors/deep
Check as well:
Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on constructor and Spring Data Query Builder Mechanism.
핵심 사항:
참조:
Dto Via Constructor Expression and JPQL
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
JOIN
Description: Using JOIN
is very useful for fetching DTOs (data that is never modified, not in the current or subsequent requests). For example, consider two entities, Author
and Book
in a lazy-bidirectional @OneToMany
association. And, we want to fetch a subset of columns from the parent table ( author
) and a subset of columns from the child table ( book
). This job is a perfect fit for JOIN
which can pick up columns from different tables and build a raw result set. This way we fetch only the needed data. Moreover, we may want to serve the result set in pages (eg, via LIMIT
). This application contains several approaches for accomplishing this task with offset pagination.
핵심 사항:
Page
(with SELECT COUNT
and COUNT(*) OVER()
window function)Slice
and List
DENSE_RANK()
for avoiding the truncation of the result set (an author can be fetched with only a subset of his books)LEFT JOIN FETCH
참조:
Description: Let's assume that we have two entities engaged in a one-to-many (or many-to-many) lazy bidirectional (or unidirectional) relationship (eg, Author
has more Book
). And, we want to trigger a single SELECT
that fetches all Author
and the corresponding Book
. This is a job for JOIN FETCH
which is converted behind the scene into a INNER JOIN
. Being an INNER JOIN
, the SQL will return only Author
that have Book
. If we want to return all Author
, including those that doesn't have Book
, then we can rely on LEFT JOIN FETCH
. Similar, we can fetch all Book
, including those with no registered Author
. This can be done via LEFT JOIN FETCH
or LEFT JOIN
.
핵심 사항:
Author
and Book
in a one-to-many lazy bidirectional relationship)LEFT JOIN FETCH
to fetch all authors and books (fetch authors even if they don't have registered books)LEFT JOIN FETCH
to fetch all books and authors (fetch books even if they don't have registered authors)JOIN
VS. JOIN FETCH
참조:
Description: This is an application meant to reveal the differences between JOIN
and JOIN FETCH
. The important thing to keep in mind is that, in case of LAZY
fetching, JOIN
will not be capable to initialize the associated collections along with their parent objects using a single SQL SELECT
. On the other hand, JOIN FETCH
is capable to accomplish this kind of task. But, don't underestimate JOIN
, because JOIN
is the proper choice when we need to combine/join the columns of two (or more) tables in the same query, but we don't need to initialize the associated collections on the returned entity (eg, very useful for fetching DTO).
핵심 사항:
Author
and Book
in a one-to-many lazy-bidirectional relationship)JOIN
and JOIN FETCH
to fetch an author including his booksJOIN
to fetch a book (1)JOIN
to fetch a book including its author (2)JOIN FETCH
to fetch a book including its author다음 사항에 유의하세요.
JOIN
, fetching Book
of Author
requires additional SELECT
statements being prone to N+1 performance penaltyJOIN
(1), fetching Author
of Book
requires additional SELECT
statements being prone to N+1 performance penaltyJOIN
(2), fetching Author
of Book
works exactly as JOIN FETCH
(requires a single SELECT
)JOIN FETCH
, fetching each Author
of a Book
requires a single SELECT
Description: If, for some reason, you need an entity in your Spring projection (DTO), then this application shows you how to do it via an example. In this case, there are two entities, Author
and Book
, involved in a lazy bidirectional one-to-many association (it can be other association as well, or even no materialized association). And, we want to fetch in a Spring projection the authors as entities, Author
, and the title
of the books.
핵심 사항:
Author
and Book
in a one-to-many lazy bidirectional relationship)public Author getAuthor()
and public String getTitle()
Description: If, for some reason, you need an entity in your Spring projection (DTO), then this application shows you how to do it via an example. In this case, there are two entities, Author
and Book
, that have no materialized association between them, but, they share the genre
attribute. We use this attribute to join authors with books via JPQL. And, we want to fetch in a Spring projection the authors as entities, Author
, and the title
of the books.
핵심 사항:
Author
and Book
)public Author getAuthor()
and public String getTitle()
Description: Let's assume that we have two entities, Author
and Book
. There is no materialized association between them, but, both entities shares an attribute named, genre
. We want to use this attribute to join the tables corresponding to Author
and Book
, and fetch the result in a DTO. The result should contain the Author
entity and only the title
attribute from Book
. Well, when you are in a scenario as here, it is strongly advisable to avoid fetching the DTO via constructor expression . This approach cannot fetch the data in a single SELECT
, and is prone to N+1. Way better than this consists of using Spring projections, JPA Tuple
or even Hibernate ResultTransformer
. These approaches will fetch the data in a single SELECT
. This application is a DON'T DO THIS example. Check the number of queries needed for fetching the data. In place, do it as here: Entity Inside Spring Projection (no association).
@ElementCollection
Description: This application is an example of fetching a DTO that includes attributes from an @ElementCollection
.
핵심 사항:
@ElementCollection
is loaded lazy, keep it lazyJOIN
in the repositorySet
Of Associated Entities In @ManyToMany
Association Via @OrderBy
Description: In case of @ManyToMany
association, we always should rely on Set
(not on List
) for mapping the collection of associated entities (entities of the other parent-side). 왜? Well, please see Prefer Set Instead of List in @ManyToMany Relationships. But, is well-known that HashSet
doesn't have a predefined entry order of elements. If this is an issue then this application relies on @OrderBy
which adds an ORDER BY
clause in the SQL statement. The database will handle the ordering. Further, Hibernate will preserve the order via a LinkedHashSet
.
This application uses two entities, Author
and Book
, involved in a lazy bidirectional many-to-many relationship. First, we fetch a Book
by title. Further, we call getAuthors()
to fetch the authors of this book. The fetched authors are ordered descending by name. The ordering is done by the database as a result of adding @OrderBy("name DESC")
, and is preserved by Hibernate.
핵심 사항:
@OrderBy
HashSet
, but doesn't provide consistency across all transition states (eg, transient state)LinkedHashSet
instead of HashSet
Note: Alternatively, we can use @OrderColumn
. This gets materialized in an additional column in the junction table. This is needed for maintaining a permanent ordering of the related data.
Description: This is a sample application that shows how versioned ( @Version
) optimistic locking and detached entity works. Running the application will result in an optimistic locking specific exception (eg, the Spring Boot specific, OptimisticLockingFailureException
).
핵심 사항:
findById(1L)
; commit transaction and close the Persistence ContextfindById(1L)
and update it; commit the transaction and close the Persistence Contextsave()
and pass to it the detached entity; trying to merge ( EntityManager.merge()
) the entity will end up in an optimistic locking exception since the version of the detached and just loaded entity don't matchOptimisticLockException
Shaped Via @Version
Note: Optimistic locking via @Version
works for detached entities as well.
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception. So, running the application should end up with a Spring specific ObjectOptimisticLockingFailureException
exception.
핵심 사항:
@Transactional
method used for updating dataIf you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
TransactionTemplate
After OptimisticLockException
Exception ( @Version
) Note: Optimistic locking via @Version
works for detached entities as well.
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception. When such exception occurs, the application retry the corresponding transaction via db-util library developed by Vlad Mihalcea.
핵심 사항:
pom.xml
, add the db-util
dependencyOptimisticConcurrencyControlAspect
beanTransactionTemplate
OptimisticLockException
In Version-less Optimistic LockingNote: Version-less optimistic locking doesn't work for detached entities (do not close the Persistence Context).
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception. So, running the application should end up with a Spring specific ObjectOptimisticLockingFailureException
exception.
핵심 사항:
@Transactional
method used for updating dataTransactionTemplate
After OptimisticLockException
Shaped Via Hibernate Version-less Optimistic Locking MechanismNote: Version-less optimistic locking doesn't work for detached entities (do not close the Persistence Context).
Description: This is a Spring Boot application that simulates a scenario that leads to an optimistic locking exception. When such exception occur, the application retry the corresponding transaction via db-util library developed by Vlad Mihalcea.
핵심 사항:
pom.xml
, add the db-util
dependencyOptimisticConcurrencyControlAspect
beanTransactionTemplate
Description: This is a sample application that shows how to take advantage of versioned optimistic locking and detached entities in HTTP long conversations. The climax consists of storing the detached entities across multiple HTTP requests. Commonly, this can be accomplished via HTTP session.
핵심 사항:
@Version
@SessionAttributes
for storing the detached entitiesSample output (check the message caused by optimistic locking exception):
@Where
Note: Rely on this approach only if you simply cannot use JOIN FETCH WHERE
or @NamedEntityGraph
.
Description: This application is a sample of using Hibernate @Where
for filtering associations.
핵심 사항:
@Where(clause = "condition to be met")
in entity (check the Author
entity)Description: Batch inserts (in MySQL) in Spring Boot style.
핵심 사항:
application.properties
set spring.jpa.properties.hibernate.jdbc.batch_size
application.properties
set spring.jpa.properties.hibernate.generate_statistics
(just to check that batching is working)application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))spring.jpa.properties.hibernate.order_inserts=true
to optimize the batching by ordering insertsIDENTITY
will cause insert batching to be disabledspring.jpa.properties.hibernate.cache.use_second_level_cache=false
출력 예:
COUNT(*) OVER
And Return Page<entity>
Via Extra Column Description: Typically, in offset pagination, there is one query needed for fetching the data and one for counting the total number of records. But, we can fetch this information in a single database rountrip via a SELECT COUNT
subquery nested in the main SELECT
. Even better, for databases vendors that support Window Functions there is a solution relying on COUNT(*) OVER()
as in this application that uses this window function in a native query against MySQL 8. So, prefer this one instead of SELECT COUNT
subquery.This application fetches data as Page<entity>
via Spring Boot offset pagination, but, if the fetched data is read-only , then rely on Page<dto>
as here.
핵심 사항:
PagingAndSortingRepository
@Column(insertable = false, updatable = false)
List<entity>
List<entity>
and Pageable
to create a Page<entity>
SELECT COUNT
Subquery And Return List<entity>
Via Extra Column Description: This application fetches data as List<entity>
via Spring Boot offset pagination. The SELECT COUNT
triggered for counting the total number of records is a subquery of the main SELECT
. Therefore, there will be a single database roundtrip instead of two (typically, one query is needed for fetching the data and one for counting the total number of records).
핵심 사항:
PagingAndSortingRepository
entity
, add an extra column for representing the total number of records and annotate it as @Column(insertable = false, updatable = false)
SELECT COUNT
subquery) into a List<entity>
SELECT COUNT
Subquery And Return List<projection>
That Maps Entities And The Total Number Of Records Via Projection Description: This application fetches data as List<projection>
via Spring Boot offset pagination. The projection maps the entity and the total number of records. This information is fetched in a single database rountrip because the SELECT COUNT
triggered for counting the total number of records is a subquery of the main SELECT
. Therefore, there will be a single database roundtrip instead of two (typically, there is one query needed for fetching the data and one for counting the total number of records). Use this approch only if the fetched data is not read-only . Otherwise, prefer List<dto>
as here.
핵심 사항:
PagingAndSortingRepository
SELECT COUNT
subquery) into a List<projection>
COUNT(*) OVER
And Return List<entity>
Via Extra Column Description: Typically, in offset pagination, there is one query needed for fetching the data and one for counting the total number of records. But, we can fetch this information in a single database rountrip via a SELECT COUNT
subquery nested in the main SELECT
. Even better, for databases vendors that support Window Functions there is a solution relying on COUNT(*) OVER()
as in this application that uses this window function in a native query against MySQL 8. So, prefer this one instead of SELECT COUNT
subquery.This application fetches data as List<entity>
via Spring Boot offset pagination, but, if the fetched data is read-only , then rely on List<dto>
as here.
핵심 사항:
PagingAndSortingRepository
entity
, add an extra column for representing the total number of records and annotate it as @Column(insertable = false, updatable = false)
COUNT(*) OVER
subquery) into a List<entity>
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
SELECT COUNT
Subquery And Return Page<entity>
Via Extra Column Description: This application fetches data as Page<entity>
via Spring Boot offset pagination. Use this only if the fetched data will be modified. Otherwise, fetch Page<dto>
as here. The SELECT COUNT
triggered for counting the total number of records is a subquery of the main SELECT
. Therefore, there will be a single database roundtrip instead of two (typically, there is one query needed for fetching the data and one for counting the total number of records).
핵심 사항:
PagingAndSortingRepository
@Column(insertable = false, updatable = false)
List<entity>
List<entity>
and Pageable
to create a Page<entity>
SELECT COUNT
Subquery And Return Page<projection>
That Maps Entities And The Total Number Of Records Via Projection Description: This application fetches data as Page<projection>
via Spring Boot offset pagination. The projection maps the entity and the total number of records. This information is fetched in a single database rountrip because the SELECT COUNT
triggered for counting the total number of records is a subquery of the main SELECT
.
핵심 사항:
PagingAndSortingRepository
List<projection>
List<projection>
and Pageable
to create a Page<projection>
COUNT(*) OVER
And Return Page<dto>
Description: Typically, in offset pagination, there is one query needed for fetching the data and one for counting the total number of records. But, we can fetch this information in a single database rountrip via a SELECT COUNT
subquery nested in the main SELECT
. Even better, for databases vendors that support Window Functions there is a solution relying on COUNT(*) OVER()
as in this application that uses this window function in a native query against MySQL 8. So, prefer this one instead of SELECT COUNT
subquery . This application return a Page<dto>
.
핵심 사항:
PagingAndSortingRepository
List<dto>
List<dto>
and Pageable
to create a Page<dto>
예:
Slice<entity>
/ Slice<dto>
Via fetchAll
/ fetchAllDto
Story : Spring Boot provides an offset based built-in paging mechanism that returns a Page
or Slice
. Each of these APIs represents a page of data and some metadata. The main difference is that Page
contains the total number of records, while Slice
can only tell if there is another page available. For Page
, Spring Boot provides a findAll()
method capable to take as arguments a Pageable
and/or a Specification
or Example
. In order to create a Page
that contains the total number of records, this method triggers an SELECT COUNT
extra-query next to the query used to fetch the data of the current page . This can be a performance penalty since the SELECT COUNT
query is triggered every time we request a page. In order to avoid this extra-query, Spring Boot provides a more relaxed API, the Slice
API. Using Slice
instead of Page
removes the need of this extra SELECT COUNT
query and returns the page (records) and some metadata without the total number of records. So, while Slice
doesn't know the total number of records, it still can tell if there is another page available after the current one or this is the last page. The problem is that Slice
work fine for queries containing the SQL, WHERE
clause (including those that uses the query builder mechanism built into Spring Data), but it doesn't work for findAll()
. This method will still return a Page
instead of Slice
therefore the SELECT COUNT
query is triggered for Slice<T> findAll(...);
.
Workaround: The trick is to simply define a method named fetchAll()
that uses JPQL and Pageable
to return Slice<entity>
, and a method named fetchAllDto()
that uses JPQL and Pageable
as well to return Slice<dto>
. So, avoid naming the method findAll()
.
사용 예:
public Slice<Author> fetchNextSlice(int page, int size) {
return authorRepository.fetchAll(PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "age")));
}
public Slice<AuthorDto> fetchNextSliceDto(int page, int size) {
return authorRepository.fetchAllDto(PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "age")));
}
Description: This application is a proof of concept for using Spring Projections(DTO) and inclusive full joins written in native SQL (for MySQL).
핵심 사항:
Author
and Book
in a lazy bidirectional @OneToMany
relationship)resources/data-mysql.sql
)AuthorNameBookTitle.java
)EhCache
) Description: This application is a sample of declaring an immutable entity. Moreover, the immutable entity will be stored in Second Level Cache via EhCache
implementation.
Key points of declaring an immutable entity:
@Immutable (org.hibernate.annotations.Immutable)
hibernate.cache.use_reference_entries configuration
to true
DataSourceBuilder
If you use the spring-boot-starter-jdbc
or spring-boot-starter-data-jpa
"starters", you automatically get a dependency to HikariCP
Note: The best way to tune the connection pool parameters consist in using Flexy Pool by Vlad Mihalcea. Via Flexy Pool you can find the optim settings that sustain high-performance of your connection pool.
Description: This is a kickoff application that set up HikariCP via DataSourceBuilder
. The jdbcUrl
is set up for a MySQL database. For testing purposes, the application uses an ExecutorService
for simulating concurrent users. Check the HickariCP report revealing the connection pool status.
핵심 사항:
@Bean
that returns the DataSource
programmatically Output sample:
@NaturalIdCache
For Skipping The Entity Identifier Retrieval Description: This is a SpringBoot - MySQL application that maps a natural business key using Hibernate @NaturalId
. This implementation allows us to use @NaturalId
as it was provided by Spring. Moreover, this application uses Second Level Cache ( EhCache
) and @NaturalIdCache
for skipping the entity identifier retrieval from the database.
핵심 사항:
EhCache
)@NaturalIdCache
for caching natural ids@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "Book")
for caching entites as well Output sample (for MySQL with IDENTITY
generator, @NaturalIdCache
and @Cache
):
@PostLoad
Description: This application is an example of calculating a non-persistent property of an entity based on the persistent entity attributes. In this case, we will use JPA, @PostLoad
.
핵심 사항:
@Transient
@PostLoad
that calculates this non-persistent property based on the persistent entity attributes@Generated
Description: This application is an example of calculating an entity persistent property at INSERT
and/or UPDATE
time via Hibernate, @Generated
.
핵심 사항:
Calculate at INSERT
time:
@Generated(value = GenerationTime.INSERT)
@Column(insertable = false)
Calculate at INSERT
and UPDATE
time:
@Generated(value = GenerationTime.ALWAYS)
@Column(insertable = false, updatable = false)
Further, apply:
방법 1:
columnDefinition
element of @Column
to specify as an SQL query expression the formula for calculating the persistent property방법 2:
CREATE TABLE
Note: In production, you should not rely on columnDefinition
. You should disable hibernate.ddl-auto
(by omitting it) or set it to validate
, and add the SQL query expression in CREATE TABLE
(in this application, check the discount
column in CREATE TABLE
, file schema-sql.sql
). Nevertheless, not even schema-sql.sql
is ok in production. The best way is to rely on Flyway or Liquibase.
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
@Formula
Description: This application is an example of calculating a non-persistent property of an entity based on the persistent entity attributes. In this case, we will use Hibernate, @Formula
.
핵심 사항:
@Transient
@Formula
@Formula
add the SQL query expression that calculates this non-persistent property based on the persistent entity attributescreated
, createdBy
, lastModified
And lastModifiedBy
In Entities Via HibernateNote: The same thing can be obtained via Spring Data JPA auditing as here.
Description: This application is an example of adding in an entity the fields, created
, createdBy
, lastModified
and lastModifiedBy
via Hibernate support. These fields will be automatically generated/populated.
핵심 사항:
abstract
class (eg, BaseEntity
) annotated with @MappedSuperclass
abstract
class, define a field named created
and annotate it with the built-in @CreationTimestamp
annotationabstract
class, define a field named lastModified
and annotate it with the built-in @UpdateTimestamp
annotationabstract
class, define a field named createdBy
and annotate it with the @CreatedBy
annotationabstract
class, define a field named lastModifiedBy
and annotate it with the @ModifiedBy
annotation@CreatedBy
annotation via AnnotationValueGeneration
@ModifiedBy
annotation via AnnotationValueGeneration
created
, createdBy
, lastModified
and lastModifiedBy
will extend the BaseEntity
schema-mysql.sql
)Description: Auditing is useful for maintaining history records. This can later help us in tracking user activities.
핵심 사항:
@Audited
@AuditTable
to rename the table used for auditingValidityAuditStrategy
for fast database reads, but slower writes (slower than the default DefaultAuditStrategy
)spring.jpa.hibernate.ddl-auto
or set it to validate
for avoiding schema generated from JPA annotationsschema-mysql.sql
and provide the SQL statements needed by Hibernate Enversspring.jpa.properties.org.hibernate.envers.default_catalog
for MySQL or spring.jpa.properties.org.hibernate.envers.default_schema
for the restDataSource
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is a kickoff for setting Flyway and MySQL DataSource
programmatically.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
DataSource
and Flyway programmaticallypostgres
And Schema public
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of migrating a PostgreSQL database via Flyway for the default database postgres
and schema public
.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
application.properties
, set the JDBC URL as follows: jdbc:postgresql://localhost:5432/postgres
classpath:db/migration
V1.1__Description.sql
, V1.2__Description.sql
, ...postgres
And Schema Created Via spring.flyway.schemas
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of migrating a schema ( bookstore
) created by Flyway via spring.flyway.schemas
in the default postgres
database. In this case, the entities should be annotated with @Table(schema = "bookstore")
.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
application.properties
, set the JDBC URL as follows: jdbc:postgresql://localhost:5432/postgres
application.properties
, add spring.flyway.schemas=bookstore
, where bookstore
is the schema that should be created by Flyway in the postgres
database (feel free to add your own database name)@Table(schema = "bookstore")
classpath:db/migration
V1.1__Description.sql
, V1.2__Description.sql
, ...DataSource
Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is a kickoff for setting Flyway and PostgreSQL DataSource
programmatically.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
DataSource
and Flyway programmatically Note: For production, don't rely on hibernate.ddl-auto
(or counterparts) to export schema DDL to the database. Simply remove (disable) hibernate.ddl-auto
or set it to validate
. Rely on Flyway or Liquibase.
Description: This application is an example of auto-creating and migrating two databases in MySQL using Flyway. In addition, each data source uses its own HikariCP connection pool. In case of MySQL, where a database is the same thing with schema, we create two databases, authorsdb
and booksdb
.
핵심 사항:
pom.xml
, add the Flyway dependencyspring.jpa.hibernate.ddl-auto
or set it to validate
application.properties
, configure the JDBC URL for booksdb
as jdbc:mysql://localhost:3306/booksdb?createDatabaseIfNotExist=true
and for authorsdb
as jdbc:mysql://localhost:3306/authorsdb?createDatabaseIfNotExist=true
application.properties
, set spring.flyway.enabled=false
to disable default behaviorDataSource
, one for booksdb
and one for authorsdb
FlywayDataSource
, one for booksdb
and one for authorsdb
EntityManagerFactory
, one for booksdb
and one for authorsdb
booksdb
, place the migration SQLs files in dbmigrationbooksdb
authorsdb
, place the migration SQLs files in dbmigrationauthorsdb
hi/lo
Algorithm And External Systems Issue Description: This is a Spring Boot sample that exemplifies how the hi/lo
algorithm may cause issues when the database is used by external systems as well. Such systems can safely generate non-duplicated identifiers (eg, for inserting new records) only if they know about the hi/lo
presence and its internal work. So, better rely on pooled
or pooled-lo
algorithm which doesn't cause such issues.
핵심 사항:
SEQUENCE
generator type (eg, in PostgreSQL)hi/lo
algorithm as in Author.java
entityhi/lo
NEXTVAL('hilo_sequence')
and is not aware of hi/lo
presence and/or behavior) Output sample: Running this application should result in the following error:
ERROR: duplicate key value violates unique constraint "author_pkey"
Detail: Key (id)=(2) already exists.
pooled
Algorithm Note: Rely on pooled-lo
or pooled
especially if, beside your application, external systems needs to insert rows in your tables. Don't rely on hi/lo
since, in such cases, it may cause errors resulted from generating duplicated identifiers.
Description: This is a Spring Boot example of using the pooled
algorithm. The pooled
is an optimization of hi/lo
. This algorithm fetched from the database the current sequence value as the top boundary identifier (the current sequence value is computed as the previous sequence value + increment_size
). This way, the application will use in-memory identifiers generated between the previous top boundary exclusive (aka, lowest boundary) and the current top boundary inclusive.
핵심 사항:
SEQUENCE
generator type (eg, in PostgreSQL)pooled
algorithm as in Author.java
entitypooled
NEXTVAL('hilo_sequence')
and is not aware of pooled
presence and/or behavior) Conclusion: In contrast to the classical hi/lo
algorithm, the Hibernate pooled
algorithm doesn't cause issues to external systems that wants to interact with our tables. In other words, external systems can concurrently insert rows in the tables relying on pooled
algorithm. Nevertheless, old versions of Hibernate can raise exceptions caused by INSERT
statements triggered by external systems that uses the lowest boundary as identifier. This is a good reason to update to Hibernate latest versions (eg, Hibernate 5.x), which have fixed this issue.
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
pooled-lo
Algorithm Note: Rely on pooled-lo
or pooled
especially if, beside your application, external systems needs to insert rows in your tables. Don't rely on hi/lo
since, in such cases, it may cause errors resulted from generating duplicated identifiers.
Description: This is a Spring Boot example of using the pooled-lo
algorithm. The pooled-lo
is an optimization of hi/lo
similar with pooled
. Only that, the strategy of this algorithm fetches from the database the current sequence value and use it as the in-memory lowest boundary identifier. The number of in-memory generated identifiers is equal to increment_size
.
핵심 사항:
SEQUENCE
generator type (eg, in PostgreSQL)pooled-lo
algorithm as in Author.java
entitypooled-lo
NEXTVAL('hilo_sequence')
and is not aware of pooled-lo
presence and/or behavior)@BatchSize
Description: This application uses Hibernate specific @BatchSize
at class/entity-level and collection-level. Consider Author
and Book
entities invovled in a bidirectional-lazy @OneToMany
association.
First use case fetches all Author
entities via a SELECT
query. Further, calling the getBooks()
method of the first Author
entity will trigger another SELECT
query that initializes the collections of the first three Author
entities returned by the previous SELECT
query. This is the effect of @BatchSize
at Author
's collection-level.
Second use case fetches all Book
entities via a SELECT
query. Further, calling the getAuthor()
method of the first Book
entity will trigger another SELECT
query that initializes the authors of the first three Book
entities returned by the previous SELECT
query. This is the effect of @BatchSize
at Author
class-level.
Note: Fetching associated collections in the same query with their parent can be done via JOIN FETCH
or entity graphs as well. Fetching children with their parents in the same query can be done via JOIN FETCH
, entity graphs and JOIN
as well.
핵심 사항:
Author
and Book
are in a lazy relationship (eg, @OneToMany
bidirectional relationship)Author
entity is annotated with @BatchSize(size = 3)
Author
's collection is annotated with @BatchSize(size = 3)
@NamedEntityGraph
) In Spring Boot Note: In a nutshell, entity graphs (aka, fetch plans ) is a feature introduced in JPA 2.1 that help us to improve the performance of loading entities. Mainly, we specify the entity's related associations and basic fields that should be loaded in a single SELECT
statement. We can define multiple entity graphs for the same entity and chain any number of entities and even use sub-graphs to create complex fetch plans . To override the current FetchType
semantics there are properties that can be set:
Fetch Graph (default), javax.persistence.fetchgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated as FetchType.LAZY
regardless of the default/explicit FetchType
.
Load Graph , javax.persistence.loadgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated according to their specified or default FetchType
.
Nevertheless, the JPA specs doesn't apply in Hibernate for the basic ( @Basic
) attributes. . 자세한 내용은 여기를 참조하세요.
Description: This is a sample application of using entity graphs in Spring Boot.
핵심 사항:
Author
and Book
, involved in a lazy bidirectional @OneToMany
associationAuthor
entity use the @NamedEntityGraph
to define the entity graph (eg, load in a single SELECT
the authors and the associatated books)AuthorRepositry
rely on Spring @EntityGraph
annotation to indicate the entity graph defined at the previous step Note: In a nutshell, entity graphs (aka, fetch plans ) is a feature introduced in JPA 2.1 that help us to improve the performance of loading entities. Mainly, we specify the entity's related associations and basic fields that should be loaded in a single SELECT
statement. We can define multiple entity graphs for the same entity and chain any number of entities and even use sub-graphs to create complex fetch plans . To override the current FetchType
semantics there are properties that can be set:
Fetch Graph (default), javax.persistence.fetchgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated as FetchType.LAZY
regardless of the default/explicit FetchType
.
Load Graph , javax.persistence.loadgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated according to their specified or default FetchType
.
Nevertheless, the JPA specs doesn't apply in Hibernate for the basic ( @Basic
) attributes. . 자세한 내용은 여기를 참조하세요.
Description: This is a sample application of using entity sub-graphs in Spring Boot. There is one example based on @NamedSubgraph
and one based on the dot notation (.) in an ad-hoc entity graph .
핵심 사항:
Author
, Book
and Publisher
( Author
and Book
are involved in a lazy bidirectional @OneToMany
relationship, Book
and Publisher
are also involved in a lazy bidirectional @OneToMany
relationship; between Author
and Publisher
there is no relationship) Using @NamedSubgraph
Author
entity define an entity graph via @NamedEntityGraph
; load the authors and the associatated books and use @NamedSubgraph
to define a sub-graph for loading the publishers associated with these booksAuthorRepository
rely on Spring @EntityGraph
annotation to indicate the entity graph defined at the previous stepUsing the dot notation (.)
PublisherRepository
define an ad-hoc entity graph that fetches all publishers with associated books, and further, the authors associated with these books (eg, @EntityGraph(attributePaths = {"books.author"})
. Note: In a nutshell, entity graphs (aka, fetch plans ) is a feature introduced in JPA 2.1 that help us to improve the performance of loading entities. Mainly, we specify the entity's related associations and basic fields that should be loaded in a single SELECT
statement. We can define multiple entity graphs for the same entity and chain any number of entities and even use sub-graphs to create complex fetch plans . To override the current FetchType
semantics there are properties that can be set:
Fetch Graph (default), javax.persistence.fetchgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated as FetchType.LAZY
regardless of the default/explicit FetchType
.
Load Graph , javax.persistence.loadgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated according to their specified or default FetchType
.
Nevertheless, the JPA specs doesn't apply in Hibernate for the basic ( @Basic
) attributes. . 자세한 내용은 여기를 참조하세요.
Description: This is a sample application of defining ad-hoc entity graphs in Spring Boot.
핵심 사항:
Author
and Book
, involved in a lazy bidirectional @OneToMany
relationshipSELECT
the authors and the associatated booksAuthorRepository
rely on Spring @EntityGraph(attributePaths = {"books"})
annotation to indicate the ad-hoc entity graph@Basic
Attributes In Hibernate And Spring Boot Note: In a nutshell, entity graphs (aka, fetch plans ) is a feature introduced in JPA 2.1 that help us to improve the performance of loading entities. Mainly, we specify the entity's related associations and basic fields that should be loaded in a single SELECT
statement. We can define multiple entity graphs for the same entity and chain any number of entities and even use sub-graphs to create complex fetch plans . To override the current FetchType
semantics there are properties that can be set:
Fetch Graph (default), javax.persistence.fetchgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated as FetchType.LAZY
regardless of the default/explicit FetchType
.
Load Graph , javax.persistence.loadgraph
The attributes present in attributeNodes
are treated as FetchType.EAGER
. The remaining attributes are treated according to their specified or default FetchType
.
Nevertheless, the JPA specs doesn't apply in Hibernate for the basic ( @Basic
) attributes. In other words, by default, attributes are annotated with @Basic
which rely on the default fetch policy. The default fetch policy is FetchType.EAGER
. These attributes are also loaded in case of fetch graph even if they are not explicitly specified via @NamedAttributeNode
. Annotating the basic attributes that should not be fetched with @Basic(fetch = FetchType.LAZY)
it is not enough. Both, fetch graph and load graph will ignore these settings as long as we don't add bytecode enhancement as well.
The main drawback consists of the fact the these basic attributes are fetched LAZY
by all other queries (eg, findById()
) not only by the queries using the entity graph, and most probably, you will not want this behavior.
Description: This is a sample application of using entity graphs with @Basic
attributes in Spring Boot.
핵심 사항:
Author
and Book
, involved in a lazy bidirectional @OneToMany
associationAuthor
entity use the @NamedEntityGraph
to define the entity graph (eg, load the authors names (only the name
basic attribute; ignore the rest) and the associatated books)@Basic(fetch = FetchType.LAZY)
AuthorRepository
rely on Spring @EntityGraph
annotation to indicate the entity graph defined at the previous stepSoftDeleteRepository
In Spring Boot ApplicationNote: Spring Data built-in support for soft deletes is discussed in DATAJPA-307.
Description: This application is an example of implementing soft deletes in Spring Data style via a repository named, SoftDeleteRepository
.
핵심 사항 :
abstract
class, BaseEntity
, annotated with @MappedSuperclass
BaseEntity
define a flag-field named deleted
(default this field to false
or in other words, not deleted)BaseEntity
classs@NoRepositoryBean
named SoftDeleteRepository
and extend JpaRepository
SoftDeleteRepository
출력 예:
SKIP_LOCKED
In MySQL 8 Description: This application is an example of how to implement concurrent table based queue via SKIP_LOCKED
in MySQL 8. SKIP_LOCKED
can skip over locks achieved by other concurrent transactions, therefore is a great choice for implementing job queues. In this application, we run two concurrent transactions. The first transaction will lock the records with ids 1, 2 and 3. The second transaction will skip the records with ids 1, 2 and 3 and will lock the records with ids 4, 5 and 6.
핵심 사항 :
Book
entity)BookRepository
setup @Lock(LockModeType.PESSIMISTIC_WRITE)
BookRepository
use @QueryHint
to setup javax.persistence.lock.timeout
to SKIP_LOCKED
org.hibernate.dialect.MySQL8Dialect
dialectSKIP_LOCKED
SKIP_LOCKED
In PostgreSQL Description: This application is an example of how to implement concurrent table based queue via SKIP_LOCKED
in PostgreSQL. SKIP_LOCKED
can skip over locks achieved by other concurrent transactions, therefore is a great choice for implementing job queues. In this application, we run two concurrent transactions. The first transaction will lock the records with ids 1, 2 and 3. The second transaction will skip the records with ids 1, 2 and 3 and will lock the records with ids 4, 5 and 6.
핵심 사항 :
Book
entity)BookRepository
setup @Lock(LockModeType.PESSIMISTIC_WRITE)
BookRepository
use @QueryHint
to setup javax.persistence.lock.timeout
to SKIP_LOCKED
org.hibernate.dialect.PostgreSQL95Dialect
dialectSKIP_LOCKED
JOINED
Description: This application is a sample of JPA Join Table inheritance strategy ( JOINED
)
핵심 사항 :
@Inheritance(strategy=InheritanceType.JOINED)
@PrimaryKeyJoinColumn
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
TABLE_PER_CLASS
Description: This application is a sample of JPA Table-per-class inheritance strategy ( TABLE_PER_CLASS
)
핵심 사항 :
IDENTITY
generator@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
@MappedSuperclass
Description: This application is a sample of using the JPA @MappedSuperclass
.
핵심 사항 :
abstract
, and is annotated with @MappedSuperclass
@MappedSuperclass
is the proper alternative to the JPA table-per-class inheritance strategyNote: Hibernate5Module is an add-on module for Jackson JSON processor which handles Hibernate datatypes; and specifically aspects of lazy-loading .
Description: By default, in Spring Boot, the Open Session in View anti-pattern is enabled. Now, imagine a lazy relationship (eg, @OneToMany
) between two entities, Author
and Book
(an author has associated more books). Next, a REST controller endpoint fetches an Author
without the associated Book
. But, the View (more precisely, Jackson), forces the lazy loading of the associated Book
as well. Since OSIV will supply the already opened Session
, the Proxy
initializations take place successfully.
Of course, the correct decision is to disable OSIV by setting it to false
, but this will not stop Jackson to try to force the lazy initialization of the associated Book
entities. Running the code again will result in an exception of type: Could not write JSON: failed to lazily initialize a collection of role: com.bookstore.entity.Author.books, could not initialize proxy - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.bookstore.entity.Author.books, could not initialize proxy - no Session .
Well, among the Hibernate5Module features we have support for dealing with this aspect of lazy loading and eliminate this exception. Even if OSIV will continue to be enabled (not recommended), Jackson will not use the Session
opened via OSIV.
핵심 사항 :
pom.xml
@Bean
that returns an instance of Hibernate5Module
Author
bean with @JsonInclude(Include.NON_EMPTY)
to exclude null
or what is considered empty from the returned JSON Note: The presence of Hibernate5Module instructs Jackson to initialize the lazy associations with default values (eg, a lazy associated collection will be initialized with null
). Hibernate5Module doesn't work for lazy loaded attributes. For such case consider this item.
profileSQL=true
In MySQL Description: View the prepared statement binding parameters via profileSQL=true
in MySQL.
핵심 사항 :
application.properties
append logger=Slf4JLogger&profileSQL=true
to the JDBC URL (eg, jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true&logger=Slf4JLogger&profileSQL=true
) Output sample:
Description: This application is an example of shuffling small results sets. DO NOT USE this technique for large results sets, since is extremely expensive.
핵심 사항 :
SELECT
query and append to it ORDER BY RAND()
RAND()
(eg, in PostgreSQL is random()
) Description: Commonly, deleting a parent and the associated children via CascadeType.REMOVE
and/or orphanRemoval=true
involved several SQL statements (eg, each child is deleted in a dedicated DELETE
statement). When the number of entities is significant, this is far from being efficient, therefore other approaches should be employed.
Consider Author
and Book
in a bidirectional-lazy @OneToMany
association. This application exposes the best way to delete the parent(s) and the associated children in four scenarios listed below. These approaches relies on bulk deletions, therefore they are not useful if you want the deletions to take advantage of automatic optimistic locking mechanisms (eg, via @Version
):
Best way to delete author(s) and the associated books via bulk deletions when:
Author
is in Persistent Context, no Book
Author
are in the Persistent Context, no Book
Author
and the associated Book
are in Persistent ContextAuthor
or Book
is in Persistent Context Note: The most efficient way to delete all entities via a bulk deletion can be done via the built-in deleteAllInBatch()
.
Description: Bulk operations (updates and deletes) are faster than batching, can benefit from indexing, but they have three main drawbacks:
@Version
is ignored), therefore the lost updates are not prevented (it is advisable to signal these updates by explicitly incrementing version
(if any is present))CascadeType.REMOVE
) and orphanRemoval
This application provides examples of bulk updates for Author
and Book
entities (between Author
and Book
there is a bidirectional lazy @OneToMany
association). Both, Author
and Book
, has a version
field.
@OneToMany
And Prefer Bidirectional @OneToMany
Relationship Description: As a rule of thumb, unidirectional @OneToMany
association is less efficient than the bidirectional @OneToMany
or the unidirectional @ManyToOne
associations. This application is a sample that exposes the DML statements generated for reads, writes and removal operations when the unidirectional @OneToMany
mapping is used.
핵심 사항 :
@OneToMany
is less efficient than bidirectional @OneToMany
association@OrderColumn
come with some optimizations for removal operations but is still less efficient than bidirectional @OneToMany
association@JoinColumn
eliminates the junction table but is still less efficient than bidirectional @OneToMany
associationSet
instead of List
or bidirectional @OneToMany
with @JoinColumn
relationship (eg, @ManyToOne @JoinColumn(name = "author_id", updatable = false, insertable = false)
) still performs worse than bidirectional @OneToMany
associationWHERE
/ HAVING
Clause Description: This application is an example of using subqueries in JPQL WHERE
clause (you can easily use it in HAVING
clause as well).
핵심 사항 :
Keep in mind that subqueries and joins queries may or may not be semantically equivalent (joins may returns duplicates that can be removed via DISTINCT
).
Even if the Execution Plan is specific to the database, historically speaking joins are faster than subqueries among different databases, but this is not a rule (eg, the amount of data may significantly influence the results). Of course, do not conclude that subqueries are just a replacement for joins that doesn't deserve attention. Tuning subqueries can increases their performance as well, but this is an SQL wide topic. So, benchmark! 기준! 기준!
As a rule of thumb, prefer subqueries only if you cannot use joins, or if you can prove that they are faster than the alternative joins.
WHERE
Part Of JPQL Query And JPA 2.1 Note: Using SQL functions in SELECT
part (not in WHERE
part) of the query can be done as here.
Description: Starting with JPA 2.1, a JPQL query can call SQL functions in the WHERE
part via function()
. This application is an example of calling the MySQL, concat_ws
function, but user defined (custom) functions can be used as well.
핵심 사항 :
function()
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Description: This application is an example of calling a MySQL stored procedure that returns a value (eg, an Integer
).
핵심 사항 :
@NamedStoredProcedureQuery
to shape the stored procedure in the entity@Procedure
in repository Description: This application is an example of calling a MySQL stored procedure that returns a result set. The application fetches entities (eg, List<Author>
) and DTO (eg, List<AuthorDto>
).
핵심 사항 :
EntiyManager
since Spring Data @Procedure
will not workDescription: This application is an example of calling a MySQL stored procedure that returns a result set (entity or DTO) via a native query.
핵심 사항 :
@Query(value = "{CALL FETCH_AUTHOR_BY_GENRE (:p_genre)}", nativeQuery = true)
JdbcTemplate
Note: Most probably you'll like to process the result set via BeanPropertyRowMapper
as here. This is less verbose than the approach used here. Nevertheless, this approach is useful to understand how the result set looks like.
Description: This application is an example of calling a MySQL stored procedure that returns a result set via JdbcTemplate
.
핵심 사항 :
JdbcTemplate
and SimpleJdbcCall
Description: This application is an example of retrieving the database auto-generated primary keys.
핵심 사항 :
getId()
JdbcTemplate
SimpleJdbcInsert
Description: A Hibernate proxy can be useful when a child entity can be persisted with a reference to its parent ( @ManyToOne
or @OneToOne
association). In such cases, fetching the parent entity from the database (execute the SELECT
statement) is a performance penalty and a pointless action. Hibernate can set the underlying foreign key value for an uninitialized proxy. This topic is discussed here.
A proxy can be unproxied via Hibernate.unproxy()
. This method is available starting with Hibernate 5.2.10.
핵심 사항 :
JpaRepository#getOne()
Hibernate.unproxy()
Boolean
To Yes/No Via AttributeConverter
Description: This application is an example of converting a Boolean
to Yes / No strings via AttributeConverter
. This kind of conversions are needed when we deal with legacy databases that connot be changed. In this case, the legacy database stores the booleans as Yes / No .
핵심 사항 :
AttributeConverter
@OManyToOne
Note: The @ManyToOne
association maps exactly to the one-to-many table relationship. The underlying foreign key is under child-side control in unidirectional or bidirectional relationship.
Description: This application shows that using only @ManyToOne
is quite efficient. On the other hand, using only @OneToMany
is far away from being efficient. Always, prefer bidirectional @OneToMany
or unidirectional @ManyToOne
. Consider two entities, Author
and Book
in a unidirectional @ManyToOne
relationship.
핵심 사항 :
JOIN FETCH
And Pageable
Pagination Description: Trying to combine JOIN FETCH
/ LEFT JOIN FETCH
and Pageable
results in an exception of type org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
. This application is a sample of how to avoid this exception.
핵심 사항 :
countQuery
Note: Fixing the above exception will lead to an warning of type HHH000104, firstResult / maxResults specified with collection fetch; applying in memory!
. If this warning is a performance issue, and most probably it is, then follow by reading here.
Description: HHH000104 is a Hibernate warning that tell us that pagination of a result set is tacking place in memory. For example, consider the Author
and Book
entities in a lazy-bidirectional @OneToMany
association and the following query:
@Transactional
@Query(value = "SELECT a FROM Author a LEFT JOIN FETCH a.books WHERE a.genre = ?1",
countQuery = "SELECT COUNT(a) FROM Author a WHERE a.genre = ?1")
Page<Author> fetchWithBooksByGenre(String genre, Pageable pageable);
Calling fetchWithBooksByGenre()
works fine only that the following warning is signaled: HHH000104: firstResult / maxResults specified with collection fetch; applying in memory!
Obviously, having pagination in memory cannot be good from performance perspective. This application implement a solution for moving pagination at database-level.
핵심 사항 :
Page
of entities in read-write or read-only modeSlice
or List
of entities in read-write or read-only modeIf you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
@Transactional(readOnly=true)
Actually Do Description: This application is meant to reveal what is the difference between @Transactional(readOnly = false)
and @Transactional(readOnly = true)
. In a nuthsell, readOnly = false
(default) fetches entites in read-write mode (managed). Before Spring 5.1, readOnly = true
just set FlushType.MANUAL/NEVER
, therefore the automatic dirty checking mechanism will not take action since there is no flush. In other words, Hibernate keep in the Persistent Context the fetched entities and the hydrated (loaded) state. By comparing the entity state with the hydrated state, the dirty checking mechanism can decide to trigger UPDATE
statements in our behalf. But, the dirty checking mechanism take place at flush time, therefore, without a flush, the hydrated state is kept in Persistent Context for nothing, representing a performance penalty. Starting with Spring 5.1, the read-only mode is propagated to Hibernate, therefore the hydrated state is discarded immediately after loading the entities. Even if the read-only mode discards the hydrated state the entities are still loaded in the Persistent Context, therefore, for read-only data, relying on DTO (Spring projection) is better.
핵심 사항 :
readOnly = false
load data in read-write mode (managed)readOnly = true
discard the hydrated state (starting with Spring 5.1)Description: This application is an example of getting the current database transaction id in MySQL. Only read-write database transactions gets an id in MySQL. Every database has a specific query for getting the transaction id. Here it is a list of these queries.
핵심 사항 :
SELECT tx.trx_id FROM information_schema.innodb_trx tx WHERE tx.trx_mysql_thread_id = connection_id()
Description: This application is a sample of inspecting the Persistent Context content via org.hibernate.engine.spi.PersistenceContext
.
핵심 사항 :
SharedSessionContractImplementor
PersistenceContext
API Description: This application is an example of using the Hibernate SPI, org.hibernate.integrator.spi.Integrator
for extracting tables metadata.
핵심 사항 :
org.hibernate.integrator.spi.Integrator
and override integrate()
method to return metadata.getDatabase()
Integrator
via LocalContainerEntityManagerFactoryBean
@ManyToOne
Relationship To A SQL Query Via The Hibernate @JoinFormula
Description: This application is an example of mapping the JPA @ManyToOne
relationship to a SQL query via the Hibernate @JoinFormula
annotation. We start with two entities, Author
and Book
, involved in a unidirectional @ManyToOne
relationship. Each book has a price. While we fetch a book by id (let's call it book A
), we want to fetch another book B
of the same author whose price is the next smaller price in comparison with book A
price.
핵심 사항 :
B
is done via @JoinFormula
Description: This application is an example of fetching a read-only MySQL database view in a JPA immutable entity.
핵심 사항 :
data-mysql.sql
fileGenreAndTitleView.java
Description: This application is an example of updating, inserting and deleting data in a MySQL database view. Every update/insert/delete will automatically update the contents of the underlying table(s).
핵심 사항 :
data-mysql.sql
fileWITH CHECK OPTION
Description: This application is an example of preventing inserts/updates of a MySQL view that are not visible through this view via WITH CHECK OPTION
. In other words, whenever you insert or update a row of the base tables through a view, MySQL ensures that the this operation is conformed with the definition of the view.
핵심 사항 :
WITH CHECK OPTION
to the viewjava.sql.SQLException: CHECK OPTION failed 'bookstoredb.author_anthology_view
Description: This application is an example of assigning a database temporary sequence of values to rows via the window function, ROW_NUMBER()
. This window function is available in almost all databases, and starting with version 8.x is available in MySQL as well.
핵심 사항 :
ROW_NUMBER()
(you will use it internally, in the query, usually in the WHERE
clause and CTEs), but, this time, let's write a Spring projection (DTO) that contains a getter for the column generated by ROW_NUMBER
as wellROW_NUMBER()
window function Output sample:
Description: This application is an example of finding top N rows of every group.
핵심 사항 :
ROW_NUMBER()
window function Output sample:
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
ROW_NUMBER()
Window Function Description: This application is an example of using ROW_NUMBER()
(and COUNT(*) OVER()
for counting all elements) window function to implement pagination.
핵심 사항 :
ROW_NUMBER()
Page
or Slice
, we return it as List
, therefore Pageable
is not used@Transactional
annotation is being ignored Description: This application is an example of fixing the case when @Transactional
annotation is ignored. Most of the time, this annotation is ignored in the following scenarios:
@Transactional
was added to a private
, protected
or package-protected
method@Transactional
was added to a method defined in the same class where it is invoked핵심 사항 :
@Transactional
methods therepublic
@Transactional
methods from other services Description: This is a Spring Boot example of using the hi/lo
algorithm and a custom implementation of SequenceStyleGenerator
for generating custom sequence IDs (eg, A-0000000001
, A-0000000002
, ...).
핵심 사항 :
SequenceStyleGenerator
and override the configure()
and generate()
methodsClob
And Blob
To byte[]
And String
Description: This application is an example of mapping Clob
and Blob
as byte[]
and String
.
핵심 사항 :
LOB
Locators Clob
And Blob
Description: This application is an example of mapping to JDBC's LOB
locators Clob
and Blob
.
핵심 사항 :
SINGLE_TABLE
Inheritance Hierarchy Description: This application is a sample of fetching a certain subclass from a SINGLE_TABLE
inheritance hierarchy. This is useful when the dedicated repository of the subclass doesn't automatically add in the WHERE
clause a dtype
based condition for fetching only the needed subclass.
핵심 사항 :
WHERE
clause a TYPE
check@NaturalId
Description: This is a SpringBoot application that defines a @ManyToOne
relationship that doesn't reference a primary key column. It references a Hibernate @NaturalId
column.
핵심 사항 :
@JoinColumn(referencedColumnName = "natural_id_column")
Specification
Description: This application is an example of implementing an advanced search via Specification
API. Mainly, you can give the search filters to a generic Specification
and fetch the result set. Pagination is supported as well. You can chain expressions via logical AND
and OR
to create compound filters. Nevertheless, there is room for extensions to add brackets support (eg, (x AND y) OR (x AND z)
), more operations, conditions parser and so on and forth.
핵심 사항 :
Specification
Specification
Query Fetch Joins Description: This application contains two examples of how to define JOIN
in Specification
to emulate JPQL join-fetch operations.
핵심 사항 :
SELECT
statements and the pagination is done in memory (very bad!)SELECT
statements but the pagination is done in the databaseJOIN
is defined in a Specification
implementationNote: You may also like to read the recipe, "How To Enrich DTO With Virtual Properties Via Spring Projections"
Description: Fetch only the needed data from the database via Spring Data Projections (DTO). The projection interface is defined as a static
interface (can be non- static
as well) in the repository interface.
핵심 사항 :
List<projection>
LIMIT
) - here, we can use query builder mechanism built into Spring Data repository infrastructureNote: Using projections is not limited to use query builder mechanism built into Spring Data repository infrastructure. We can fetch projections via JPQL or native queries as well. For example, in this application we use a JPQL.
Output example (select first 2 rows; select only "name" and "age"):
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Description: Consider an entity named Review
. This entity defines three @ManyToOne
relationships to Book
, Article
and Magazine
. A review can be associated with either a book, a magazine or an article. To validate this constraint, we can rely on Bean Validation as in this application.
핵심 사항 :
null
@JustOneOfMany
) added at class-level to the Review
entityTRIGGER
) Description: This application uses EnumType.ORDINAL
and EnumType.STRING
for mapping Java enum
type to database. As a rule of thumb, strive to keep the data types as small as possible (eg, for EnumType.ORDINAL
use TINYINT/SMALLINT
, while for EnumType.STRING
use VARCHAR(max_needed_bytes)
). Relying on EnumType.ORDINAL
should be more efficient but is less expressive than EnumType.STRING
.
핵심 사항 :
EnumType.ORDINAL
set @Column(columnDefinition = "TINYINT")
)enum
To Database Via AttributeConverter
Description: This application maps a Java enum
via AttributeConverter
. In other words, it maps the enum
values HORROR
, ANTHOLOGY
and HISTORY
to the integers 1
, 2
and 3
and viceversa. This allows us to set the column type as TINYINT/SMALLINT
which is less space-consuming than VARCHAR(9)
needed in this case.
핵심 사항 :
AttributeConverter
@Converter
the corresponding entity fieldenum
To PostgreSQL enum
Type Description: This application maps a Java enum
type to PostgreSQL enum
type.
핵심 사항 :
EnumType
EnumType
via package-info.java
@Type
enum
To PostgreSQL enum
Type Via Hibernate Types Library Description: This application maps a Java enum
type to PostgreSQL enum
type via Hibernate Types library.
핵심 사항 :
pom.xml
@TypeDef
to specify the needed type class@Type
Description: Hibernate Types is a library of extra types not supported by Hibernate Core by default. This is a Spring Boot application that uses this library to persist JSON data (JSON Java Object
) in a MySQL json
column and for querying JSON data from the MySQL json
column to JSON Java Object
. Updates are supported as well.
핵심 사항 :
pom.xml
@TypeDef
to map typeClass
to JsonStringType
Description: Hibernate Types is a library of extra types not supported by Hibernate Core by default. This is a Spring Boot application that uses this library to persist JSON data (JSON Java Object
) in a PostgreSQL json
column and for querying JSON data from the PostgreSQL json
column to JSON Java Object
. Updates are supported as well.
핵심 사항 :
pom.xml
@TypeDef
to map typeClass
to JsonBinaryType
OPTIMISTIC_FORCE_INCREMENT
Description: This application is a sample of how OPTIMISTIC_FORCE_INCREMENT
works in MySQL. This is useful when you want to increment the version of the locked entity even if this entity was not modified. Via OPTIMISTIC_FORCE_INCREMENT
the version is updated (incremented) at the end of the currently running transaction.
핵심 사항 :
Chapter
(which uses @Version
)Modification
entityModification
(child-side) and Chapter
(parent-side) there is a lazy unidirectional @ManyToOne
associationINSERT
statement against the modification
table, therefore the chapter
table will not be modified by editorsChapter
entity version is needed to ensure that modifications are applied sequentially (the author and editor are notified if a modificaton was added since the chapter copy was loaded)version
is forcibly increased at each modification (this is materialized in an UPDATE
triggered against the chapter
table at the end of the currently running transaction)OPTIMISTIC_FORCE_INCREMENT
in the corresponding repositoryObjectOptimisticLockingFailureException
PESSIMISTIC_FORCE_INCREMENT
Description: This application is a sample of how PESSIMISTIC_FORCE_INCREMENT
works in MySQL. This is useful when you want to increment the version of the locked entity even if this entity was not modified. Via PESSIMISTIC_FORCE_INCREMENT
the version is updated (incremented) immediately (the entity version update is guaranteed to succeed immediately after acquiring the row-level lock). The incrementation takes place before the entity is returned to the data access layer.
핵심 사항 :
Chapter
(which uses @Version
)Modification
entityModification
(child-side) and Chapter
(parent-side) there is a lazy unidirectional @ManyToOne
associationINSERT
statement against the modification
table, therefore the chapter
table will not be modified by editorsChapter
entity version
is needed to ensure that modifications are applied sequentially (each editor is notified if a modificaton was added since his chapter copy was loaded and he must re-load the chapter)version
is forcibly increased at each modification (this is materialized in an UPDATE
triggered against the chapter
table immediately after aquiring the row-level lock)PESSIMISTIC_FORCE_INCREMENT
in the corresponding repositoryOptimisticLockException
and one that will lead to QueryTimeoutException
Note: Pay attention to the MySQL dialect: MySQL5Dialect
(MyISAM) doesn't support row-level locking, MySQL5InnoDBDialect
(InnoDB) acquires row-level lock via FOR UPDATE
(timeout can be set), MySQL8Dialect
(InnoDB) acquires row-level lock via FOR UPDATE NOWAIT
.
PESSIMISTIC_READ
And PESSIMISTIC_WRITE
Works In MySQL Description: This application is an example of using PESSIMISTIC_READ
and PESSIMISTIC_WRITE
in MySQL. In a nutshell, each database system defines its own syntax for acquiring shared and exclusive locks and not all databases support both types of locks. Depending on Dialect
, the syntax can vary for the same database as well (Hibernate relies on Dialect
for chosing the proper syntax). In MySQL, MySQL5Dialect
doesn't support locking, while InnoDB engine ( MySQL5InnoDBDialect
and MySQL8Dialect
) supports shared and exclusive locks as expected.
핵심 사항 :
@Lock(LockModeType.PESSIMISTIC_READ)
and @Lock(LockModeType.PESSIMISTIC_WRITE)
on query-levelTransactionTemplate
to trigger two concurrent transactions that read and write the same rowIf you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
PESSIMISTIC_WRITE
Works With UPDATE
/ INSERT
And DELETE
Operations Description: This application is an example of triggering UPDATE
, INSERT
and DELETE
operations in the context of PESSIMISTIC_WRITE
locking against MySQL. While UPDATE
and DELETE
are blocked until the exclusive lock is released, INSERT
depends on the transaction isolation level. Typically, even with exclusive locks, inserts are possible (eg, in PostgreSQL). In MySQL, for the default isolation level, REPEATABLE READ
, inserts are prevented against a range of locked entries, but, if we switch to READ_COMMITTED
, then MySQL acts as PostgreSQL as well.
핵심 사항 :
SELECT
with PESSIMISTIC_WRITE
to acquire an exclusive lockUPDATE
, INSERT
or DELETE
on the rows locked by Transaction AUPDATE
, DELETE
and INSERT
+ REPEATABLE_READ
, Transaction B is blocked until it timeouts or Transaction A releases the exclusive lockINSERT
+ READ_COMMITTED
, Transaction B can insert in the range of rows locked by Transaction A even if Transaction A is holding an exclusive lock on this range Note: Do not test transaction timeout via Thread.sleep()
! This is not working! Rely on two transactions and exclusive locks or even better rely on SQL sleep functions (eg, MySQL, SELECT SLEEP(n)
seconds, PostgreSQL, SELECT PG_SLEEP(n)
seconds). Most RDBMS supports a sleep function flavor.
Description: This application contains several approaches for setting a timeout period for a transaction or query. The timeout is signaled by a specific timeout exception (eg, .QueryTimeoutException
). After timeout, the transaction is rolled back. You can see this in the database (visually or query) and on log via a message of type: Initiating transaction rollback; Rolling back JPA transaction on EntityManager [SessionImpl(... <open>)]
.
핵심 사항 :
spring.transaction.default-timeout
in seconds (see, application.properties
)@Transactional(timeout = n)
in secondsjavax.persistence.query.timeout
hint in millisecondsorg.hibernate.timeout
hint in seconds Note: If you are using TransactionTemplate
then the timeout can be set via TransactionTemplate.setTimeout(n)
in seconds.
@Embeddable
Description: This application is a proof of concept of how to define a composite key via @Embeddable
and @EmbeddedId
. This application uses two entities, Author
and Book
involved in a lazy bidirectional @OneToMany
association. The identifier of Author
is composed by name
and age
via AuthorId
class. The identifier of Book
is just a regular auto-generated numeric value.
핵심 사항 :
AuthorId
) is public
Serializable
equals()
and hashCode()
@IdClass
Description: This application is a proof of concept of how to define a composite key via @IdClass
. This application uses two entities, Author
and Book
involved in a lazy bidirectional @OneToMany
association. The identifier of Author
is composed by name
and age
via AuthorId
class. The identifier of Book
is just a typical auto-generated numeric value.
핵심 사항 :
AuthorId
) is public
Serializable
equals()
and hashCode()
Note : The @IdClass
can be useful when we cannot modify the compsite key class. Otherwise, rely on @Embeddable
.
@Embeddable
Composite Primary Key Description: This application is a proof of concept of how to define a relationship in an @Embeddable
composite key. The composite key is AuthorId
and it belongs to the Author
class.
핵심 사항 :
AuthorId
) is public
Serializable
equals()
and hashCode()
Description: This is a SpringBoot application that loads multiple entities by id via a @Query
based on the IN
operator and via the Hibernate 5 MultiIdentifierLoadAccess
interface.
핵심 사항 :
IN
operator in a @Query
simply add the query in the proper repositoryMultiIdentifierLoadAccess
in Spring Data style provide the proper implementationMultiIdentifierLoadAccess
implementation allows us to load entities by multiple ids in batches and by inspecting or not the current Persistent Context (by default, the Persistent Context is not inspected to see if the entities are already loaded or not) Description: This application is a sample of fetching all attributes of an entity ( Author
) as a Spring projection (DTO). Commonly, a DTO contains a subset of attributes, but, sometimes we need to fetch the whole entity as a DTO. In such cases, we have to pay attention to the chosen approach. Choosing wisely can spare us from performance penalties.
핵심 사항 :
List<Object[]>
or List<AuthorDto>
via a JPQL of type SELECT a FROM Author a
WILL fetch the result set as entities in Persistent Context as well - avoid this approachList<Object[]>
or List<AuthorDto>
via a JPQL of type SELECT a.id AS id, a.name AS name, ... FROM Author a
will NOT fetch the result set in Persistent Context - this is efficientList<Object[]>
or List<AuthorDto>
via a native SQL of type SELECT id, name, age, ... FROM author
will NOT fetch the result set in Persistent Context - but, this approach is 꽤 느림List<Object[]>
via Spring Data query builder mechanism WILL fetch the result set in Persistent Context - avoid this approachList<AuthorDto>
via Spring Data query builder mechanism will NOT fetch the result set in Persistent ContextfindAll()
method) should be considered after JPQL with explicit list of columns to be fetched and query builder mechanism@ManyToOne
Or @OneToOne
Associations Description: This application fetches a Spring projection including the @ManyToOne
association via different approaches. It can be easily adapted for @OneToOne
association as well.
핵심 사항 :
Description: This application inspect the Persistent Context content during fetching Spring projections that includes collections of associations. In this case, we focus on a @OneToMany
association. Mainly, we want to fetch only some attributes from the parent-side and some attributes from the child-side.
Description: This application is a sample of reusing an interface-based Spring projection. This is useful to avoid defining multiple interface-based Spring projections in order to cover a range of queries that fetches different subsets of fields.
핵심 사항 :
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
annotation to avoid serialization of default fields (eg, fields that are not available in the current projection and are null
- these fields haven't been fetched in the current query)null
fields)If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Description: This application is a sample of using dynamic Spring projections.
핵심 사항 :
<T> List<T> findByGenre(String genre, Class<T> type);
) Description: This application is a sample of batching inserts via EntityManager
in MySQL. This way you can easily control the flush()
and clear()
cycles of the Persistence Context (1st Level Cache) inside the current transaction. This is not possible via Spring Boot, saveAll(Iterable<S> entities)
, since this method executes a single flush per transaction. Another advantage is that you can call persist()
instead of merge()
- this is used behind the scene by the SpringBoot saveAll(Iterable<S> entities)
and save(S entity)
.
Moreover, this example commits the database transaction after each batch excecution. This way we avoid long-running transactions and, in case of a failure, we rollback only the failed batch and don't lose the previous batches. For each batch, the Persistent Context is flushed and cleared, therefore we maintain a thin Persistent Context. This way the code is not prone to memory errors and performance penalties caused by slow flushes.
핵심 사항 :
application.properties
set spring.jpa.properties.hibernate.jdbc.batch_size
application.properties
set spring.jpa.properties.hibernate.generate_statistics
(just to check that batching is working)application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))spring.jpa.properties.hibernate.order_inserts=true
to optimize the batching by ordering insertsIDENTITY
will cause insert batching to be disabledspring.jpa.properties.hibernate.cache.use_second_level_cache=false
출력 예:
Description: This is a Spring Boot application that reads a relatively big JSON file (200000+ lines) and inserts its content in MySQL via batching using ForkJoinPool
, JdbcTemplate
and HikariCP.
핵심 사항 :
json
typeList
rewriteBatchedStatements=true
-> this setting will force sending the batched statements in a single request;cachePrepStmts=true
-> enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disableduseServerPrepStmts=true
-> this way you switch to server-side prepared statements (may lead to signnificant performance boost); moreover, you avoid the PreparedStatement
to be emulated at the JDBC Driver level;...?cachePrepStmts=true&useServerPrepStmts=true&rewriteBatchedStatements=true&createDatabaseIfNotExist=true
StopWatch
to measure the time needed to transfer the file into the databasecitylots.zip
in the current location; this is the big JSON file collected from Internet;DatasourceProxyBeanPostProcessor.java
component by uncomment the line, // @Component
; This is needed because this application relies on DataSource-Proxy (for details, see the following item)CompletableFuture
Description: This application is a sample of using CompletableFuture
for batching inserts. This CompletableFuture
uses an Executor
that has the number of threads equal with the number of your computer cores. Usage is in Spring style.
Description: Let's suppose that we have a one-to-many relationship between Author
and Book
entities. When we save an author, we save his books as well thanks to cascading all/persist. We want to create a bunch of authors with books and save them in the database (eg, a MySQL database) using the batch technique. By default, this will result in batching each author and the books per author (one batch for the author and one batch for the books, another batch for the author and another batch for the books, and so on). In order to batch authors and books, we need to order inserts as in this application.
Moreover, this example commits the database transaction after each batch excecution. This way we avoid long-running transactions and, in case of a failure, we rollback only the failed batch and don't lose the previous batches. For each batch, the Persistent Context is flushed and cleared, therefore we maintain a thin Persistent Context. This way the code is not prone to memory errors and performance penalties caused by slow flushes.
핵심 사항 :
application.properties
the following property: spring.jpa.properties.hibernate.order_inserts=true
Example without ordered inserts:
Example with ordered inserts:
Description: Batch inserts (in MySQL) in Spring Boot style. This example commits the database transaction after each batch excecution. This way we avoid long-running transactions and, in case of a failure, we rollback only the failed batch and don't lose the previous batches.
핵심 사항 :
application.properties
set spring.jpa.properties.hibernate.jdbc.batch_size
application.properties
set spring.jpa.properties.hibernate.generate_statistics
(just to check that batching is working)application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))spring.jpa.properties.hibernate.order_inserts=true
to optimize the batching by ordering insertsIDENTITY
will cause insert batching to be disabledspring.jpa.properties.hibernate.cache.use_second_level_cache=false
출력 예:
IN
Clause Parameter Padding Description: This application is an example of using Hibernate IN
cluase parameter padding. This way we can reduce the number of Execution Plans. Mainly, Hibernate is padding parameters as follows:
핵심 사항 :
application.properties
set spring.jpa.properties.hibernate.query.in_clause_parameter_padding=true
Description: Fetch only the needed data from the database via Spring Data Projections (DTO). In this case, via class-based projections.
핵심 사항 :
equals()
and hashCode()
only for the columns that should be fetched from the databaseList<projection>
LIMIT
)Note: Using projections is not limited to use query builder mechanism built into Spring Data repository infrastructure. We can fetch projections via JPQL or native queries as well. For example, in this application we use a JPQL.
Output example (select first 2 rows; select only "name" and "age"):
Description: Batch inserts via Hibernate session-level batching (Hibernate 5.2 or higher) in MySQL. This example commits the database transaction after each batch excecution. This way we avoid long-running transactions and, in case of a failure, we rollback only the failed batch and don't lose the previous batches. For each batch, the Persistent Context is flushed and cleared, therefore we maintain a thin Persistent Context. This way the code is not prone to memory errors and performance penalties caused by slow flushes.
핵심 사항 :
application.properties
set spring.jpa.properties.hibernate.generate_statistics
(just to check that batching is working)application.properties
set JDBC URL with rewriteBatchedStatements=true
(optimization for MySQL)application.properties
set JDBC URL with cachePrepStmts=true
(enable caching and is useful if you decide to set prepStmtCacheSize
, prepStmtCacheSqlLimit
, etc as well; without this setting the cache is disabled)application.properties
set JDBC URL with useServerPrepStmts=true
(this way you switch to server-side prepared statements (may lead to signnificant performance boost))spring.jpa.properties.hibernate.order_inserts=true
to optimize the batching by ordering insertsIDENTITY
will cause insert batching to be disabledSession
is obtained by un-wrapping it via EntityManager#unwrap(Session.class)
Session#setJdbcBatchSize(Integer size)
and get via Session#getJdbcBatchSize()
spring.jpa.properties.hibernate.cache.use_second_level_cache=false
출력 예:
Description: This application highlights the difference betweeen loading entities in read-write vs. read-only mode. If you plan to modify the entities in a future Persistent Context then fetch them as read-only in the current Persistent Context.
핵심 사항 :
Note: If you never plan to modify the fetched result set then use DTO (eg, Spring projection), not read-only entities.
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Note: Domain events should be used with extra-caution! The best practices for using them are revealed in my book, Spring Boot Persistence Best Practices.
Description: Starting with Spring Data Ingalls release publishing domain events by aggregate roots becomes easier. Entities managed by repositories are aggregate roots. In a Domain-Driven Design application, these aggregate roots usually publish domain events. Spring Data provides an annotation @DomainEvents
you can use on a method of your aggregate root to make that publication as easy as possible. A method annotated with @DomainEvents
is automatically invoked by Spring Data whenever an entity is saved using the right repository. Moreover, Spring Data provides the @AfterDomainEventsPublication
annotation to indicate the method that should be automatically called for clearing events after publication. Spring Data Commons comes with a convenient template base class ( AbstractAggregateRoot
) to help to register domain events and is using the publication mechanism implied by @DomainEvents
and @AfterDomainEventsPublication
. The events are registered by calling the AbstractAggregateRoot.registerEvent()
method. The registered domain events are published if we call one of the save methods (eg, save()
) of the Spring Data repository and cleared after publication.
This is a sample application that relies on AbstractAggregateRoot
and its registerEvent()
method. We have two entities, Book
and BookReview
involved in a lazy-bidirectional @OneToMany
association. A new book review is saved in CHECK
status and a CheckReviewEvent
is published. This event handler is responsible to check the review grammar, content, etc and switch the review status from CHECK
to ACCEPT
or REJECT
and propagate the new status to the database. So, this event is registered before saving the book review in CHECK
status and is published automatically after we call the BookReviewRepository.save()
method. After publication, the event is cleared.
핵심 사항 :
AbstractAggregateRoot
and provide a method for registering eventsCheckReviewEvent
), but more can be registeredCheckReviewEventHandler
in an asynchronous manner via @Async
Description: This application is an example of testing the Hibernate Query Plan Cache (QPC). Hibernate QPC is enabled by default and, for entity queries (JPQL and Criteria API), the QPC has a size of 2048, while for native queries it has a size of 128. Pay attention to alter these values to accommodate all queries executed by your 애플리케이션. If the number of exectued queries is higher than the QPC size (especially for entity queries) then you will start to experiment performance penalties caused by entity compilation time added for each query execution.
In this application, you can adjust the QPC size in application.properties
. Mainly, there are 2 JPQL queries and a QPC of size 2. Switching from size 2 to size 1 will cause the compilation of one JPQL query at each execution. Measuring the times for 5000 executions using a QPC of size 2, respectively 1 reveals the importance of QPC in terms of time.
핵심 사항 :
hibernate.query.plan_cache_max_size
hibernate.query.plan_parameter_metadata_max_size
Description: This is a SpringBoot application that enables Hibernate Second Level Cache and EhCache provider. It contains an example of caching entities and an example of caching a query result.
핵심 사항 :
EhCache
)@Cache
HINT_CACHEABLE
Description: This is a SpringBoot application representing a kickoff application for Spring Boot caching and EhCache
.
핵심 사항 :
EhCache
SqlResultSetMapping
And NamedNativeQuery
Note: If you want to rely on the {EntityName}.{RepositoryMethodName}
naming convention for simply creating in the repository interface methods with the same name as of native named query then skip this application and check this one.
Description: This is a sample application of using SqlResultSetMapping
, NamedNativeQuery
and EntityResult
for fetching single entity and multiple entities as List<Object[]>
.
핵심 사항 :
SqlResultSetMapping
, NamedNativeQuery
and EntityResult
Description: This is a SpringBoot application that loads multiple entities by id via a @Query
based on the IN
operator and via Specification
.
핵심 사항 :
IN
operator in a @Query
simply add the query in the proper repositorySpecification
rely on javax.persistence.criteria.Root.in()
ResultTransformer
Description: Fetching more read-only data than needed is prone to performance penalties. Using DTO allows us to extract only the needed data. Sometimes, we need to fetch a DTO made of a subset of properties (columns) from a parent-child association. For such cases, we can use SQL JOIN
that can pick up the desired columns from the involved tables. But, JOIN
returns an List<Object[]>
and most probably you will need to represent it as a List<ParentDto>
, where a ParentDto
instance has a List<ChildDto>
. For such cases, we can rely on a custom Hibernate ResultTransformer
. This application is a sample of writing a custom ResultTransformer
.
핵심 사항 :
ResultTransformer
interface Description: Is a common scenario to have a big List
and to need to chunk it in multiple smaller List
of given size. For example, if we want to employee a concurrent batch implementation we need to give to each thread a sublist of items. Chunking a list can be done via Google Guava, Lists.partition(List list, int size)
method or Apache Commons Collections, ListUtils.partition(List list, int size)
method. But, it can be implemented in plain Java as well. This application exposes 6 ways to do it. The trade-off is between the speed of implementation and speed of execution. For example, while the implementation relying on grouping collector is not performing very well, it is quite simple and fast to write it.
핵심 사항 :
Chunk.java
class which relies on the built-in List.subList()
method Time-performance trend graphic for chunking 500, 1_000_000, 10_000_000 and 20_000_000 items in lists of 5 items:
Description: Consider the Book
and Chapter
entities. A book has a maximum accepted number of pages ( book_pages
) and the author should not exceed this number. When a chapter is ready for review, the author is submitting it. At this point, the publisher should check that the currently total number of pages doesn't exceed the allowed book_pages
:
This kind of checks or constraints are easy to implement via database triggers. This application relies on a MySQL trigger to empower our complex contraint ( check_book_pages
).
핵심 사항 :
AFTER INSERT OR AFTER UPDATE
) Description: This application is an example of using Spring Data Query By Example (QBE) to check if a transient entity exists in the database. Consider the Book
entity and a Spring controller that exposes an endpoint as: public String checkBook(@Validated @ModelAttribute Book book, ...)
. Beside writting an explicit JPQL, we can rely on Spring Data Query Builder mechanism or, even better, on Query By Example (QBE) API. In this context, QBE API is quite useful if the entity has a significant number of attributes and:
핵심 사항 :
BookRepository
extends QueryByExampleExecutor
<S extends T> boolean exists(Example<S> exmpl)
with the proper probe (an entity instance populated with the desired fields values)ExampleMatcher
which defines the details on how to match particular fields Note: Do not conclude that Query By Example (QBE) defines only the exists()
method. Check out all methods here.
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
@Transactional
Description: This application is meant to highlight that the best place to use @Transactional
for user defined query-methods is in repository interface, and afterwards, depending on situation, on service-methods level.
핵심 사항 :
JOINED
Inheritance Strategy And Visitor Design Pattern Description: This application is an example of using JPA JOINED
inheritance strategy and Visitor pattern.
핵심 사항 :
JOINED
Inheritance Strategy And Strategy Design Pattern Description: This application is an example of using JPA JOINED
inheritance strategy and Strategy pattern.
핵심 사항 :
Description: This folder holds several applications that shows how each Spring transaction propagation works.
핵심 사항 :
GenerationType.AUTO
And UUID Identifiers Description: This application is an example of using the JPA GenerationType.AUTO
for assigning automatically UUID identifiers.
핵심 사항 :
BINARY(16)
columnDescription: This application is an example of manually assigning UUID identifiers.
핵심 사항 :
BINARY(16)
columnuuid2
For Generating UUID Identifiers Description: This application is an example of using the Hibernate RFC 4122 compliant UUID generator, uuid2
.
핵심 사항 :
BINARY(16)
columnDescription: This Spring Boot application is a sample that reveals how Hibernate session-level repeatable reads works. Persistence Context guarantees session-level repeatable reads. Check out how it works.
핵심 사항 :
TransactionTemplate
Note: For a detailed explanation of this application consider my book, Spring Boot Persistence Best Practices
hibernate.enable_lazy_load_no_trans
Description: This application is an example of using Hibernate-specific hibernate.enable_lazy_load_no_trans
. Check out the application log to see how transactions and database connections are used.
핵심 사항 :
hibernate.enable_lazy_load_no_trans
Description: This application is an example of cloning entities. The best way to achieve this goal relies on copy-constructors. This way we can control what we copy. Here we use a bidirectional-lazy @ManyToMany
association between Author
and Book
.
핵심 사항 :
Author
(only the genre
) and associate the corresponding booksAuthor
(only the genre
) and clone the books as wellIf you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
UPDATE
Statement Only The Modified Columns Via Hibernate @DynamicUpdate
Description: This application is an example of using the Hibernate-specific, @DynamicUpdate
. By default, even if we modify only a subset of columns, the triggered UPDATE
statements will include all columns. By simply annotating the corresponding entity at class-level with @DynamicUpdate
the generated UPDATE
statement will include only the modified columns.
핵심 사항 :
UPDATE
for different subsets of columns via JDBC statements caching (each triggered UPDATE
string will be cached and reused accordingly)Description: This application is an example of logging execution time for a repository query-method.
핵심 사항 :
RepositoryProfiler
) Description: This application is an example of using the TransactionSynchronizationAdapter
for overriding beforeCommit()
, beforeCompletion()
, afterCommit()
and afterCompletion()
callbacks globally (application-level) and at method-level.
핵심 사항 :
TransactionProfiler
)TransactionSynchronizationManager.registerSynchronization()
SqlResultSetMapping
And NamedNativeQuery
Using {EntityName}.{RepositoryMethodName}
Naming Convention Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on SqlResultSetMapping
, NamedNativeQuery
and the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of native named query.
핵심 사항 :
SqlResultSetMapping
, NamedNativeQuery
SqlResultSetMapping
And NamedNativeQuery
Using {EntityName}.{RepositoryMethodName}
Naming Convention Description: This is a sample application of using SqlResultSetMapping
, NamedNativeQuery
and EntityResult
for fetching single entity and multiple entities as List<Object[]>
. In this application we rely on the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of native named query.
핵심 사항 :
SqlResultSetMapping
, NamedNativeQuery
and EntityResult
@NamedQuery
And Spring Projection (DTO) Description: This application is an example of combining JPA named queries @NamedQuery
and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named query.
핵심 사항 :
@NamedNativeQuery
And Spring Projection (DTO) Description: This application is an example of combining JPA named native queries @NamedNativeQuery
and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named native query.
핵심 사항 :
Description: JPA named (native) queries are commonly written via @NamedQuery
and @NamedNativeQuery
annotations in entity classes. Spring Data allows us to write our named (native) queries in a typical *.properties
file inside the META-INF
folder of your classpath. This way, we avoid modifying our entities. This application shows you how to do it.
Warning: Cannot use native queries with dynamic sorting ( Sort
). Nevertheless, using Sort
in named queries works fine. Moreover, using Sort
in Pageable
works fine for both, named queries and named native queries. At least this is how it behave in Spring Boot 2.2.2. From this point of view, this approach is better than using @NamedQuery
/ @NamedNativeQuery
or orm.xml
file.
핵심 사항 :
META-INF/jpa-named-queries.properties
{EntityName}.{RepositoryMethodName}
naming convention for a quick and slim implementationorm.xml
File Description: JPA named (native) queries are commonly written via @NamedQuery
and @NamedNativeQuery
annotations in entity classes. Spring Data allows us to write our named (native) queries in a typical orm.xml
file inside the META-INF
folder of your classpath. This way, we avoid modifying our entities. This application shows you how to do it.
Warning: Pay attention that, via this approach, we cannot use named (native) queries with dynamic sorting ( Sort
). Using Sort
in Pageable
is ignored, therefore you need to explicitly add ORDER BY
in the queries. At least this is how it behave in Spring Boot 2.2.2. A better approach relies on using a properties file for listing the named (native) queries. In this case, dynamic Sort
works for named queries, but not for named native queries. Using Sort
in Pageable
works as expected in named (native) queries.
핵심 사항 :
META-INF/orm.xml
{EntityName}.{RepositoryMethodName}
naming convention for a quick and slim implementation Description: JPA named (native) queries are commonly written via @NamedQuery
and @NamedNativeQuery
annotations in entity classes. This application shows you how to do it.
Warning: Pay attention that, via this approach, we cannot use named (native) queries with dynamic sorting ( Sort
). Using Sort
in Pageable
is ignored, therefore you need to explicitly add ORDER BY
in the queries. At least this is how it behave in Spring Boot 2.2.2. A better approach relies on using a properties file for listing the named (native) queries. In this case, dynamic Sort
works for named queries, but not for named native queries. Using Sort
in Pageable
works as expected in named (native) queries. And, you don't need to modify/pollute entitites with the above annotations.
핵심 사항 :
@NamedQuery
and @NamedNativeQuery
annotations in entity classes{EntityName}.{RepositoryMethodName}
naming convention for a quick and slim implementationSort
and Pageable
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
Description: This application is an example of combining JPA named queries listed in a properties file and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named query.
핵심 사항 :
jpa-named-queries.properties
) in a folder named META-INF
the application classpath Description: This application is an example of combining JPA named native queries listed in a properties file and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named native query.
핵심 사항 :
jpa-named-queries.properties
) in a folder named META-INF
the application classpathorm.xml
File And Spring Projection (DTO) Description: This application is an example of combining JPA named queries listed in orm.xml
file and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named query.
핵심 사항 :
orm.xml
file in a folder named META-INF
the application classpathorm.xml
File And Spring Projection (DTO) Description: This application is an example of combining JPA named native queries listed in orm.xml
file and Spring projections (DTO). For queries names we use the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of named native query.
핵심 사항 :
orm.xml
file in a folder named META-INF
the application classpathorm.xml
Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on named native queries and result set mapping via orm.xml
and the {EntityName}.{RepositoryMethodName}
naming convention. This convention allows us to create in the repository interface methods with the same name as of native named query.
핵심 사항 :
<named-native-query/>
and <sql-result-set-mapping/>
to map the native query to AuthorDto
classDescription: This application is a proof of concept for using Spring Projections(DTO) and cross joins written via JPQL and native SQL (for MySQL).
핵심 사항 :
Book
and Format
resources/data-mysql.sql
)BookTitleAndFormatType.java
)JdbcTemplate
And BeanPropertyRowMapper
Description: This application is an example of calling a MySQL stored procedure that returns a result set via JdbcTemplate
and BeanPropertyRowMapper
.
핵심 사항 :
JdbcTemplate
, SimpleJdbcCall
and BeanPropertyRowMapper
@EntityListeners
Description: This application is a sample of using the JPA @MappedSuperclass
and @EntityListeners
with JPA callbacks.
핵심 사항 :
Book
, is not an entity, it can be abstract
, and is annotated with @MappedSuperclass
and @EntityListeners(BookListener.class)
BookListener
defines JPA callbacks (eg, @PrePersist
)Book
is persisted, loaded, updated, etc the corresponding JPA callbacks are called@Fetch(FetchMode.JOIN)
May Causes N+1 Issues Advice: Always evaluate JOIN FETCH
and entities graphs before deciding to use FetchMode.JOIN
. The FetchMode.JOIN
fetch mode always triggers an EAGER
load so the children are loaded when the parents are. Beside this drawback, FetchMode.JOIN
may return duplicate results. You'll have to remove the duplicates yourself (eg storing the result in a Set
). But, if you decide to go with FetchMode.JOIN
at least pay attention to avoid N+1 issues discussed below.
Note: Let's assume three entities, Author
, Book
and Publisher
. Between Author
and Book
there is a bidirectional-lazy @OneToMany
association. Between Author
and Publisher
there is a unidirectional-lazy @ManyToOne
. Between Book
and Publisher
there is no association.
Now, we want to fetch a book by id ( BookRepository#findById()
), including its author, and the author's publisher. In such cases, using Hibernate fetch mode, @Fetch(FetchMode.JOIN)
works as expected. Using JOIN FETCH
or entity graph is also working as expected.
Next, we want to fetch all books ( BookRepository#findAll()
), including their authors, and the authors publishers. In such cases, using Hibernate fetch mode, @Fetch(FetchMode.JOIN)
will cause N+1 issues. It will not trigger the expected JOIN
. In this case, using JOIN FETCH
or entity graph should be used.
핵심 사항 :
@Fetch(FetchMode.JOIN)
doesn't work for query-methods@Fetch(FetchMode.JOIN)
works in cases that fetches the entity by id (primary key) like using EntityManager#find()
, Spring Data, findById()
, findOne()
.RANK()
Description: This application is an example of assigning a database temporary ranking of values to rows via the window function, RANK()
. This window function is available in almost all databases, and starting with version 8.x is available in MySQL as well.
핵심 사항 :
RANK()
(you will use it internally, in the query, usually in the WHERE
clause and CTEs), but, this time, let's write a Spring projection (DTO) that contains a getter for the column generated by RANK()
as wellRANK()
window function Output sample:
If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
DENSE_RANK()
Description: This application is an example of assigning a database temporary ranking of values to rows via the window function, DENSE_RANK()
. In comparison with the RANK()
window function, DENSE_RANK()
avoid gaps within partition. This window function is available in almost all databases, and starting with version 8.x is available in MySQL as well.
핵심 사항 :
DENSE_RANK()
(you will use it internally, in the query, usually in the WHERE
clause and CTEs), but, this time, let's write a Spring projection (DTO) that contains a getter for the column generated by DENSE_RANK()
as wellDENSE_RANK()
window function Output sample:
NTILE(N)
Description: This application is an example of distributing the number of rows in the specified (N) number of groups via the window function, NTILE(N)
. This window function is available in almost all databases, and starting with version 8.x is available in MySQL as well.
핵심 사항 :
NTILE()
(you will use it internally, in the query, usually in the WHERE
clause and CTEs), but, this time, let's write a Spring projection (DTO) that contains a getter for the column generated by NTILE()
as wellNTILE()
window function Output sample:
Description: Spring Data comes with the Query Builder mechanism for JPA that is capable to interpret a query method name (known as a derived query) and convert it into a SQL query in the proper dialect. This is possible as long as we respect the naming conventions of this mechanism. Beside the well-known query of type find...
, Spring Data supports derived count queries and derived delete queries.
핵심 사항 :
count...
(eg, long countByGenre(String genre)
) - Spring Data will generate a SELECT COUNT(...) FROM ...
querydelete...
or remove...
and returns long
(eg, long deleteByGenre(String genre)
) - Spring Data will trigger first a SELECT
to fetch entities in the Persistence Context, and, afterwards, it triggers a DELETE
for each entity that must be deleteddelete...
or remove...
and returns List<entity>
(eg, List<Author> removeByGenre(String genre)
) - Spring Data will trigger first a SELECT
to fetch entities in the Persistence Context, and, afterwards, it triggers a DELETE
for each entity that must be deletedDescription: Property expressions can refer to a direct property of the managed entity. However, you can also define constraints by traversing nested properties. This application is a sample of traversing nested properties for fetching entities and DTOs.
핵심 사항 :
Author
has several Book
and each book has several Review
(between Author
and Book
there is a bidirectional-lazy @oneToMany
association, and, between Book
and Review
there is also a bidirectional-lazy @OneToMany
association)Review
and we want to know the Author
of the Book
that has received this Review
AuthorRepository
the following query that will be processed by the Spring Data Query Builder mechanism: Author findByBooksReviews(Review review);
SELECT
with two LEFT JOIN
books.reviews
. The algorithm starts by interpreting the entire part ( BooksReviews
) as the property and checks the domain class for a property with that name (uncapitalized). If the algorithm succeeds, it uses that property. If not, the algorithm splits up the source at the camel case parts from the right side into a head and a tail and tries to find the corresponding property — in our example, Books
and Reviews
. If the algorithm finds a property with that head, it takes the tail and continues building the tree down from there, splitting the tail up in the way just described. If the first split does not match, the algorithm moves the split point to the left and continues.Author
class has an booksReview
property as well. The algorithm would match in the first split round already, choose the wrong property, and fail (as the type of booksReview
probably has no code property). To resolve this ambiguity you can use _ inside your method name to manually define traversal points. So our method name would be as follows: Author findByBooks_Reviews(Review review);
Note: Fetching read-only data should be done via DTO, not managed entities. But, there is no tragedy to fetch read-only entities in a context as follows:
@Transactional(readOnly = true)
Under these circumstances, let's tackle a common case that I saw quite a lot. There is even an SO answer about it (don't do this):
Description: Let's assume that Author
and Book
are involved in a bidirectional-lazy @OneToMany
association. Imagine an user that loads a certain Author
(without the associated Book
). The user may be interested or not in the Book
, therefore, we don't load them with the Author
. If the user is interested in the Book
then he will click a button of type, View books . Now, we have to return the List<Book>
associated to this Author
.
So, at first request (query), we fetch an Author
. The Author
is detached. At second request (query), we want to load the Book
associated to this Author
. But, we don't want to load the Author
again (for example, we don't care about lost updates of Author
), we just want to load the associated Book
in a single SELECT
. A common (not recommended) approach is to load the Author
again (eg, via findById(author.getId())
) and call the author.getBooks()
. But, this end up in two SELECT
statements. One SELECT
for loading the Author
, and another SELECT
after we force the collection initialization. We force collection initialization because it will not be initialize if we simply return it. In order to trigger the collection initialization the developer call books.size()
or he rely on Hibernate.initialize(books);
.
But, we can avoid such solution by relying on an explicit JPQL or Query Builder property expressions. This way, there will be a single SELECT
and no need to call size()
or Hibernate.initialize();
핵심 사항 :
This item is detailed in my book, Spring Boot Persistence Best Practices.
Description: Behind the built-in Spring Data save()
there is a call of EntityManager#persist()
or EntityManager#merge()
. It is important to know this aspect in several cases. Among this cases, we have the entity update case (simple update or update batching).
Consider Author
and Book
involved in a bidirectional-lazy @OneToMany
association. And, we load an Author
, detach it, update it in the detached state, and save it to the database via save()
method. Calling save()
will come with the following two issues resulting from calling merge()
behind the scene:
SELECT
(merge) and one UPDATE
SELECT
will contain a LEFT OUTER JOIN
to fetch the associated Book
as well (we don't need the books!) How about triggering only the UPDATE
instead of this? The solution relies on calling Session#update()
. Calling Session.update()
requires to unwrap the Session
via entityManager.unwrap(Session.class)
.
핵심 사항 :
Session.update()
will trigger only the UPDATE
(there is no SELECT
)Session.update()
works with versioned optimistic locking mechanism as well (so, lost updates are prevented)Streamable
Description: This application is a sample of fetching Streamable<entity>
and Streamable<dto>
. But, more important, this application contains three examples of how to not use Streamable
. It is very tempting and comfortable to fetch a Streamable
result set and chop it via filter()
, map()
, flatMap()
, and so on until we obtain only the needed data instead of writing a query (eg, JPQL) that fetches exactly the needed result set from the database. Mainly, we just throw away some of the fetched data to keep only the needed data. But, is not advisable to follow such practices because fetching more data than needed can cause significant performance penalties.
Moreover, pay attention to combining two or more Streamable
via the and()
method. The returned result may be different from what you are expecting to see. Each Streamable
produces a separate SQL statement and the final result set is a concatenation of the intermediate results sets (prone to duplicate values).
핵심 사항:
map()
)filter()
)Streamable
via and()
; each Streamable
produces a separate SQL statement and the final result set is a concatenation of the intermediate results sets (prone to duplicate values)Streamable
Wrapper TypesDescription: A common practice consists of exposing dedicated wrappers types for collections resulted after mapping a query result set. This way, on a single query execution, the API can return multiple results. After we call a query-method that return a collection, we can pass it to a wrapper class by manually instantiation of that wrapper-class. But, we can avoid the manually instantiation if the code respects the following key points.
핵심 사항 :
Streamable
static
factory method named of(…)
or valueOf(…)
taking Streamable
as argumentDescription: JPA 2.1 come with schema generation features. This feature can setup the database or export the generated commands to a file. The parameters that we should set are:
spring.jpa.properties.javax.persistence.schema-generation.database.action
: Instructs the persistence provider how to setup the database. Possible values include: none
, create
, drop-and-create
, drop
javax.persistence.schema-generation.scripts.action
: Instruct the persistence provider which scripts to create. Possible values include: none
, create
, drop-and-create
, drop
.
javax.persistence.schema-generation.scripts.create-target
: Indicate the target location of the create script generated by the persistence provider. This can be as a file URL or a java.IO.Writer
.
javax.persistence.schema-generation.scripts.drop-target
: Indicate the target location of the drop script generated by the persistence provider. This can be as a file URL or a java.IO.Writer
.
Moreover, we can instruct the persistence provider to load data from a file into the database via: spring.jpa.properties.javax.persistence.sql-load-script-source
. The value of this property represents the file location and it can be a file URL or a java.IO.Writer
.
핵심 사항 :
application.properties
Description: Sometimes, we need to write in repositories certain query-methods that return a Map
instead of a List
or a Set
. For example, when we need a Map<Id, Entity>
or we use GROUP BY
and we need a Map<Group, Count>
. This application shows you how to do it via default
methods directly in repository.
핵심 사항 :
default
methods and Collectors.toMap()
Description: Consider one of the JPA inheritance strategies (eg, JOINED
). Handling entities inheritance With Spring Data repositories can be done as follows:
Description: This application is a sample of logging only slow queries via Hibernate 5.4.5, hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS
property. A slow query is a query that has an execution time bigger than a specificed threshold in milliseconds.
핵심 사항 :
application.properties
add hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS
출력 예:
Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on JDK14 Records feature and Spring Data Query Builder Mechanism.
From Openjdk JEP359:
Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data.
Key points: Define the AuthorDto
as:
public record AuthorDto(String name, int age) implements Serializable {}
Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on JDK 14 Records, Constructor Expression and JPQL.
From Openjdk JEP359:
Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data.
핵심 사항 :
Define the AuthorDto
as:
public record AuthorDto(String name, int age) implements Serializable {}
ResultTransformer
Description: Fetching more read-only data than needed is prone to performance penalties. Using DTO allows us to extract only the needed data. Sometimes, we need to fetch a DTO made of a subset of properties (columns) from a parent-child association. For such cases, we can use SQL JOIN
that can pick up the desired columns from the involved tables. But, JOIN
returns an List<Object[]>
and most probably you will need to represent it as a List<ParentDto>
, where a ParentDto
instance has a List<ChildDto>
. For such cases, we can rely on a custom Hibernate ResultTransformer
. This application is a sample of writing a custom ResultTransformer
.
As DTO, we rely on JDK 14 Records. From Openjdk JEP359:
Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data.
핵심 사항 :
AuthorDto
and BookDto
ResultTransformer
interfaceJdbcTemplate
And ResultSetExtractor
Description: Fetching more data than needed is prone to performance penalities. Using DTO allows us to extract only the needed data. In this application we rely on JDK14 Records feature, JdbcTemplate
and ResultSetExtractor
.
From Openjdk JEP359:
Records provide a compact syntax for declaring classes which are transparent holders for shallowly immutable data.
핵심 사항 :
AuthorDto
and BookDto
JdbcTemplate
and ResultSetExtractor
Description: This application is a sample of using dynamic Spring projections via DTO classes.
핵심 사항 :
<T> List<T> findByGenre(String genre, Class<T> type);
)If you need a deep dive into the performance recipes exposed in this repository then I am sure that you will love my book "Spring Boot Persistence Best Practices" | If you need a hand of tips and illustrations of 100+ Java persistence performance issues then "Java Persistence Performance Illustrated Guide" is for you. |
CompletableFuture
And Return List<S>
Description: This application is a sample of using CompletableFuture
for batching inserts. This CompletableFuture
uses an Executor
that has the number of threads equal with the number of your computer cores. Usage is in Spring style. It returns List<S>
:
CompletableFuture
And Return List<S>
(1)CompletableFuture
And Return List<S>
(2) Description: This application is an example of causing a database deadlock in MySQL. This application produces an exception of type: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
. However, the database will retry until transaction (A) succeeds.
핵심 사항 :
SELECT
with PESSIMISTIC_WRITE
to acquire an exclusive lock to table author
author
genre with success and sleeps for 10sSELECT
with PESSIMISTIC_WRITE
to acquire an exclusive lock to table book
book
title with success and sleeps for 10s Description: This application is a proof of concept of how to define a composite key having an explicit part ( name
) and a generated part ( authorId
via SEQUENCE
generator).
핵심 사항 :
@IdClass
Description: Sometimes we need to intercept the generated SQL that originates from Spring Data, EntityManager
, Criteria API, JdbcTemplate
and so on. This can be done as in this sample application. After interception, you can log, modify or even return a brand new SQL that will be executed in the end.
핵심 사항 :
StatementInspector
SPIapplication.properties
via spring.jpa.properties.hibernate.session_factory.statement_inspector
281. Force inline params in Criteria API
NOTE Use this with high precaution since you open the gate for SQL injections.
Description: Sometimes we need to force inline params in Criteria API. By default, numeric parameters are inlined, but string parameters are not.
핵심 사항:
application.properties
the setting spring.jpa.properties.hibernate.criteria.literal_handling_mode
as inline
Description: Arthur Gavlyukovskiy provide a suite of Spring Boot starters for quickly integrate P6Spy, Datasource Proxy, and FlexyPool. In this example, we add Datasource Proxy, but please consider this for more details.
핵심 사항 :
pom.xml
, add the datasource-proxy-spring-boot-starter
starterapplication.properties
enable DEBUG
level for loggingDescription: This application is an example of using Java records as embeddable. This is available starting with Hibernate 6.0, but it was refined to be more accessible and easy to use in Hibernate 6.2
핵심 사항 :
Contact
)Author
) via @Embedded
AuthorDto
)