【问题标题】:Hibernate generates different queries for same codeHibernate 为相同的代码生成不同的查询
【发布时间】:2021-10-18 15:45:43
【问题描述】:

我们刚刚修复了 Hibernate 中的一个行为,在该行为中,它在本地计算机上生成的查询与在暂存服务器上生成的查询不同。谁能给我解释一下,为什么

@NotNull
@OneToOne(fetch = FetchType.EAGER)
@Type(type = "user_account")
open var user: T

在本地翻译成

来自
用户密码摘要pa0_
left external join user_account basicaccou1_ on abstractpa0_.user_id=basicaccou1_.id

在服务器上,在 Kubernetes 上运行 dockerized,它被翻译成

来自用户密码摘要pa0_
左外连接 d21_user_account useraccoun1_ on abstractpa0_.user_id = useraccoun1_.id
左外连接 user_account useraccoun1_1_ on useraccoun1_.id = useraccoun1_1_.id

我们使用单表继承策略。基类是AbstractPasswordEntity

@Entity(name = "user_password")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "user_type")
abstract class AbstractPasswordEntity<T : BasicAccountEntity>(

    ...

    @NotNull
    @OneToOne(fetch = FetchType.EAGER)
    @Type(type = "user_account")
    open var user: T

) : BaseEntity()

由客户实施

@Entity(name = "CustomerPassword")
@DiscriminatorValue("CustomerPasswordEntity")
class CustomerPasswordEntity(

    id: Long? = null,
    passwordHash: String,
    user: CustomerAccountEntity

) : AbstractPasswordEntity<CustomerAccountEntity>(..., user)

和员工课程。

@Entity(name = "StaffPassword")
@DiscriminatorValue("StaffPasswordEntity")
class StaffPasswordEntity(

    id: Long? = null,
    passwordHash: String,
    user: StaffAccountEntity

) : AbstractPasswordEntity<StaffAccountEntity>(..., user)

我们可以通过将AbstractPasswordEntity 中的关系注释更改为

来修复一天的错误修复和大量 WTF 后的行为
@Entity(name = "user_password")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "user_type")
abstract class AbstractPasswordEntity<T : BasicAccountEntity>(

    ...

    @NotNull
    @OneToOne(fetch = FetchType.EAGER, targetEntity = BasicAccountEntity::class)
    open var user: T

) : BaseEntity()

这现在以相同的方式在所有环境中编译和执行。我唯一不知道的是刚刚发生了什么以及为什么发生。

Funfact:与 pkgdiff 和 md5deep 相比,staging 和本地的 jar 显示完全相同的结果 - 除了 GitLab 属性。

【问题讨论】:

    标签: hibernate spring-data-jpa


    【解决方案1】:

    由于这个话题无法得到任何回复,以下是我们的最佳猜测:

    这是泛型的问题。它们在运行时被删除,我们遇到了排序问题。它在本地运行,因为偶然地,hibernate 中的类的顺序导致了预期的结果。在暂存时,顺序会混淆,hibernate 使用第一个适合类的泛型,然后导致执行不同的查询。所以明确指定父 BasicAccountEntity 作为入口点确实解决了它的问题。

    正如我所说,最好的猜测。

    【讨论】:

      猜你喜欢
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 2014-09-24
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多