Spring Boot& Spring Data:Hibernate会话如何管理? [英] Spring Boot & Spring Data: how are Hibernate Sessions managed?
问题描述
我目前正在使用Spring Boot和Spring Data(它的 JpaRepository
接口是精确的)和Hibernate一起使用。
我喜欢Hiberante的一件事是它的缓存功能 - 当您提交与特定对象匹配的多个查询时,您将在每次查询执行时返回该对象的相同实例(关于Java的==运营商)。但是,当使用Spring Data和 JpaRepository
类时,似乎并非总是如此。因此,我假设这里有多个 HibernateSession
实例。
因此,我的问题是:如何Spring Data处理休眠会话?它何时打开或关闭它们?有没有办法将它配置为在我的应用程序的整个运行时使用相同的会话来充分利用Hibernate的对象缓存? 是否有理由这样做?
谢谢,
Alan
我想我自己找到了答案。如果有人发现这个问题,这里是我的答案。
Spring如何管理Hibernate会话?
$ b $当调用
JpaRepository
方法(或者通常任何 Repository
方法)时,Spring将: - 询问
SessionFactory
创建新会话 - 打开本节点
- 执行被调用的
存储库
方法 >
对于使用Spring @Transactional
注释进行注释的任何方法似乎都适用。
后果如何?
作为程序员... p>
- 您不必关心事务或会话。
- 您不能依赖Hibernate缓存功能。这只适用于
HibernateSession
。 - ,您必须决定您的
@Entity
对象的Hibernate ID值,而不是使用Java的==
运算符。 - 您需要注意(
@OneToMany
引用)中的< FetchMode.LAZY ,而不是FetchMode.EAGER
)仅用于@Transactional
-annotated method
另外供参考,以下链接相当有用:> 与Spring的许多其他方面,如果您愿意牺牲对您的应用程序的直接控制,那么在这里可以获得很多。 I am currently working on an application that uses Spring Boot and Spring Data (its One thing I love about Hiberante is its caching feature - when you submit multiple queries that match a particular object, you will get back the same instance of that object on every query execution (with respect to Java's == operator). However, when using Spring Data and My question therefore is: how does Spring Data handle Hibernate Sessions? When does it open or close them? Is there a way to configure it to use the same session for the entire runtime of my application to make full use of Hibernate's object cache? Is there a reason not to do it that way? Thanks, Alan I think I've found the answer myself. If somebody finds this question, here's my answer. How does Spring manage Hibernate Sessions? When calling a The same thing seems to hold for any method annotated with the Spring What are the consequences? As a programmer... Also for reference, the following link has been quite helpful: Multiple Transactions in single session As with many other aspects of Spring, there is a lot to be gained here, if you are willing to sacrifice direct control over your application. 这篇关于Spring Boot& Spring Data:Hibernate会话如何管理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
JpaRepository
interfaces to be precise) together with Hibernate.JpaRepository
classes, this does not always seem to be the case. For that reason, I assume that there are multiple HibernateSession
instances at work here.JpaRepository
method (or in general any Repository
method), Spring will:
SessionFactory
to create a new sessionRepository
method@Transactional
annotation.
HibernateSession
.@Entity
objects by their Hibernate ID value, rather than by using Java's ==
operator.@OneToMany
reference) in your @Entity
classes (see FetchMode.LAZY
as opposed to FetchMode.EAGER
) are used exclusively within an @Transactional
-annotated method