当我使用实体映射的共享主键时,我对Hibernate创建的sql有问题。我使用的是JPA 2.1和Hibernate 5.2.2
这是我的实体:
@Entity
@Column(name = "employee_table")
public class EmployeeEntity {
@Id
@Column(name = "id")
@SequenceGenerator
@GeneratedValue
private Long id;
@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
private EmployeeDetailsEntity employeeDetailsEntity;
}
@Entity
@Table(name = "employee_details")
public class EmployeeDetailsEntity {
@Id
@Column(name = "id")
private Long id;
// additional attributes
}
我想选择所有具有详细信息的员工:
select e from EmployeeEntity e where e.employeeDetailsEntity is not null;
选择由Hibernate生成的:
select employeeen0_.id from employee_table employeeen0_ where employeeen0_.id is not null;
请你解释一下我做错了什么并帮助解决这个问题?
答案 0 :(得分:1)
看起来你错过了"另一方"员工 - > EmployeeDetails关系映射:
员工实体:
private EmployeeDetails employeeDetails;
@OneToOne(mappedBy = "employee", fetch = FetchType.LAZY)
public EmployeeDetails getEmployeeDetails() {
return employeeDetails;
}
EmployeeDetails实体:
private Employee employee;
@OneToOne(optional = false)
@JoinColumn(name = "EMPLOYEE_ID")
public Employee getEmployee() {
return employee;
}
答案 1 :(得分:-1)
感谢所有评论的人。 问题是使用EmployeeEntity主键在EmployeeDetailsEntity上的@PrimaryKeyJoinColumn,并且在你的hql中检查本机sql Hibernate的null(或非null)的EmployeeDetailsEntity使用了EmployeeEntity的id,因为你与另一个(EmployeeDetailsEntity)实体共享这个PK。
如果您不想(不能)改变您的映射,请在您的hql查询中使用join或更改@OneToOne映射。