Skip to content

Commit

Permalink
add jpa query timeout and tests for it (#244)
Browse files Browse the repository at this point in the history
* add jpa query timeout and tests for it

* add check exception message, unit for timeout, checkstyle

---------

Co-authored-by: m.zharinova <[email protected]>
Co-authored-by: Ivan Vakhrushev <[email protected]>
  • Loading branch information
3 people authored Oct 8, 2024
1 parent e6f05e1 commit 5279eb8
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ spring:
hibernate:
dialect: org.hibernate.dialect.PostgreSQLDialect
enable_lazy_load_no_trans: false
jakarta:
persistence:
query:
timeout: 1000 # 1 second
main:
banner-mode: off
profiles:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.mfvanek.salary.calc.repositories;

import com.mfvanek.salary.calc.support.TestBase;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import jakarta.persistence.QueryTimeoutException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class JpaPropertiesTest extends TestBase {

@Autowired
EntityManager entityManager;

@Test
void failsWhenQueryTooLong() {
final Query query = entityManager
.createNativeQuery(
"SELECT pg_sleep(5)");
assertThatThrownBy(query::getResultList)
.isInstanceOf(QueryTimeoutException.class)
.hasMessageContaining("ERROR: canceling statement due to user request");
}

@Test
@DisplayName("Does not throw exception when query does not exceed timeout")
void exceptionWithNotLongQuery() {
final Query query = entityManager
.createNativeQuery(
"SELECT pg_sleep(3.9)");
assertThatNoException().isThrownBy(query::getResultList);
}
}
7 changes: 7 additions & 0 deletions src/test/resources/application-test.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
logging:
level:
org.springframework.orm.jpa.JpaTransactionManager: DEBUG
spring:
jpa:
properties:
jakarta:
persistence:
query:
timeout: 4000 # milliseconds

0 comments on commit 5279eb8

Please sign in to comment.