I am currently investigating the following issue, which also affects our production environment https://github.com/querydsl/querydsl/issues/3089. A author of this library suspected that Hibernate might be the culprit of the issue, and i was able to reproduce this with a minimal example. Before opening an issue in the Hibernate issue tracker i wanted to make sure that i am not doing anything horribly wrong or it actually is an issue with Spring.
I am using the following versions:
- Spring-Boot 3.0.5 (older versions are also affected)
- Hibernate 6.1.7 FINAL (older versions are also affected)
Calling the following controller is causing the connection leak, which Hikari also picks up and logs in the output.
@Controller
public class IndexController {
@PersistenceContext
private EntityManager entityManager;
@GetMapping("/test")
public ResponseEntity<Map<Long, String>> fetchEntities() {
Query query = entityManager.createQuery("select testEntity.id, testEntity.name from TestEntity testEntity");
org.hibernate.query.Query<?> unwrappedQuery = query.unwrap(org.hibernate.query.Query.class);
try (ScrollableResults<?> results = unwrappedQuery.scroll()) {
while (results.next()) {}
}
return ResponseEntity.noContent().build();
}
}
The connection also leaks, if i call entityManager.close
and/or results.close()
With this entity:
@Entity
@Table(name = "test")
public class TestEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
public TestEntity() {
}
public TestEntity(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my database config:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = { DatabaseConfig.class })
@EntityScan(basePackageClasses = { DatabaseConfig.class })
public class DatabaseConfig {
}
My application config:
management:
server:
base-path: /actuator
port: 8081
endpoints.web.exposure.include: '*'
spring:
datasource:
url: jdbc:h2:mem:testdb
driver-class-name: org.h2.Driver
username:
password:
hikari:
leak-detection-threshold: 2000
jpa:
open-in-view: false
hibernate:
ddl-auto: create
properties:
hibernate:
dialect: org.hibernate.dialect.H2Dialect
logging:
level:
com.zaxxer.hikari.pool.HikariPool: debug