gpt4 book ai didi

java - Hibernate vs Spring 连接获取策略

转载 作者:行者123 更新时间:2023-12-01 17:23:05 25 4
gpt4 key购买 nike

我试图了解在使用 hibernate 作为 ORM 和 Spring 进行事务管理的应用程序中何时确切地获取数据库连接。

this文章中写道:

If the transaction manager decides to create a new transaction, then it will:

create a new entity manager

bind the entity manager to the current thread

grab a connection from the DB connection pool

bind the connection to the current thread

但是here它说:

Hibernate defers the database connection acquisition until the current transaction has to execute its first SQL statement (either triggered by a read or a write operation). This optimization allows Hibernate to reduce the physical transaction interval, therefore increasing the chance of getting a connection from the pool.

我不明白如果 Spring 决定提前获取连接,Hibernate 如何延迟连接获取。

最佳答案

I can't understand how can Hibernate delay the connection aquisitionif Spring decides to aquire it before.

该决定由事务管理器做出,因此可能由JpaTransactionManager/HibernateTransactionManager

Hibernate 5.2.0 引入了新属性 hibernate.connection.provider_disables_autocommit

有了这个Hibernate就可以延迟数据库连接的获取,直到有一条JDBC语句要执行。否则进入@Transactional服务方法时获取数据库连接。

因此,为了允许 Spring 在设置 Spring 上下文期间将此属性连接到 JPATransactionManager 中,您必须在 application.properties/yaml 中设置此属性 -->

spring.jpa.properties.hibernate.connection.provider_disables_autocommit=true

执行此操作所需的最后一件事 --> 在连接池提供程序上将 AutoCommit 设置为 false(自 Spring boot 2 以来默认为 HikariCP)

spring.datasource.hikari.auto-commit=false

关于java - Hibernate vs Spring 连接获取策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61255353/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com