使用 JPA 和 Hibernate 6 将数据保留在 Spanner 中

问题描述 投票:0回答:1

我正在致力于将扳手与我们现有的应用程序集成。当尝试使用 JPA 和 hibernate 6 将数据保存/保留到 spanner 中的 DemoClass 实体时,我遇到错误。我面临的错误如下

Error: Number of joins exceeds the maximum allowed limit of 20.

实体类

@Entity
DemoClass extends CommonClass{
...
...

//getter and setter
}

@MappedSuperClass
CommonClass implements Serializable {

@CreationTimeStamp
Timestamp CreatedTime;

@CreationTimeStamp
Timestamp updatedTime;

@OneToOne
Demo2 createdUser;

@OneToOne
Demo2 updatedUser;

//getter and setter
}

@Entity
Demo2 extends CommonClass {
...
...

//getter and setter
}

来自 pom.xml 的依赖项

spring-boot-starter-parent: 3.3.5
spring-boot-starter-data-jpa
google-cloud-spanner-hibernate-dialect: 3.7.1
google-cloud-spanner: 6.81.2
spring-cloud-gcp-data-spanner: 5.8.0
google-cloud-spanner-jdbc : 2.24.1
hibernate-types-60: 2.21.1

spring-boot hibernate jpa spring-data-jpa google-cloud-spanner
1个回答
0
投票

您遇到的错误“连接数超过允许的最大限制 20”通常发生在查询涉及太多表连接时,这可能与实体关系的设置方式有关,尤其是使用 @OneToOne 时CommonClass 和 Demo2 实体中的关联。

这里有一些可以尝试的事情:

  • 检查延迟加载:默认情况下,@OneToOne关系是急切加载的,这可能会导致在持久化或查询数据时触发多个连接。尝试将关系注释为 @OneToOne(fetch = FetchType.LAZY) 以避免在持久化操作期间加载不必要的相关实体。
@OneToOne(fetch = FetchType.LAZY)
Demo2 createdUser;

@OneToOne(fetch = FetchType.LAZY)
Demo2 updatedUser;
  • 检查实体结构:由于您正在扩展 CommonClass,它本身具有 @OneToOne 关系,因此请确保这些关系不会导致不必要或过多的连接。在某些情况下,@MappedSuperclass 可能会多次包含在查询中,从而导致许多联接。如果关系深度太复杂,您还可以考虑重构模型。

  • 优化查询:检查生成的 SQL 查询(通过日志记录)并查看是否存在过多或意外的连接。您也许能够优化它们或简化持久性逻辑。您可以通过将其添加到您的 application.properties 来启用 Hibernate SQL 日志记录:

spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.generate_statistics=true
© www.soinside.com 2019 - 2024. All rights reserved.