gpt4 book ai didi

java - JPA InheritanceType 的 @PrimaryKeyJoinColumn 在 COUNT 查询中无法正常工作

转载 作者:行者123 更新时间:2023-12-01 22:39:39 26 4
gpt4 key购买 nike

有一些这样的类:

@Entity
@Table(name="person")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {
@Id
@GeneratedValue
private int personId;

它的子类是:

@Entity
@Table(name="employee")
@PrimaryKeyJoinColumn(name="employee_id")
public class Employee extends Person {
[Something else fields]

需要提到的是,还有一些其他对象是从 Person 扩展的,例如具有自己的 Fk 字段(例如 Student_id)的 Student 到 Person 实体。

生成的以下 HQL 查询:

select count(e) 
from Employee e

是:

select count(e.id)
from employee e
inner join person p
on e.employee_id = p.id

而正确生成的查询必须是:

select count(e.employee_id)
from employee e
inner join person p
on e.employee_id = p.id

因此会引发无效标识符异常。

哪里出了问题,我需要做什么来解决这个问题?

更新

这些实体的表是:

人:

id                and others files
------------------------------------

员工表是:

employee_id[fk to person table]         others fields
----------------------------------------------------

最佳答案

虽然 Hibernate 允许这种类型的继承,但通常会避免这种情况,因为开发人员难以控制结果/行为。

相反,根据我之前的经验和恕我直言,我建议遵循以下实践,这将使您能够更好地控制自 JPA 2.0 以来使用 @JoinColumn 来实现预期结果:

@Entity
@Table(name="person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="person_id")
private Long personId;

}
@Entity
@Table(name="employee")
public class Employee{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="employee_id")
private Long employeeId;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn (name="person_id")
private Person person;

}
<小时/>

更新1

如果更喜欢使用@PrimaryKeyJoinColumn,那么原始代码中需要纠正一件事(至少需要为 PK 分配一个名称以给您更多控制权:

@Entity
@Table(name="person")
@Inheritance(strategy=InheritanceType.JOINED)
public class Person {

@Id
@GeneratedValue
@Column(name="person_id")
private int personId;
}
@Entity
@Table(name="employee")
@PrimaryKeyJoinColumn(name="person_id")
public class Employee extends Person {

@GeneratedValue
@Column(name="employee_id")
private int employeeId;

}

这是因为@PrimaryKeyJoinColumn是为了让当前从表知道它需要引用主表的哪个主键。

您可以引用 JPA 2.0 规范的以下部分:

11.1.40 PrimaryKeyJoinColumn Annotation

The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.

The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108].

关于java - JPA InheritanceType 的 @PrimaryKeyJoinColumn 在 COUNT 查询中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58504275/

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