在不传递主键的情况下通过 Hibernate 获取数据

Fetching Data through Hibernate without passing Primary Key

我正在使用实体 Class 中定义的复合主键:

@EmbeddedId
private ParticipantPrimaryKey pKey;

并且主键由事件 ID 和学生 ID 组成,它们在主键实体 Class 中定义。

现在我需要从 table 中获取参与任何特定事件的参与者。

由于上述问题,HQL 查询无法正常工作:

select pe from ParticipantEntity pe where pe.eventId=?

如果我使用任何其他字段,那么它会工作,因为它们存在于实体中 Class 但事件 ID 存在于主键实体中。

您可以使用 @ClassId, :

 @ClassId(ParticipantPrimaryKey.class)
 class ParticipantEntity { ...

ParticipantEntity 中删除:

@EmbeddedId
private ParticipantPrimaryKey pKey;

并且还在 ParticipantEntity 中添加两个键:

@Id
private Long eventId;

@Id
private Long studentId;

之后,您可以:

SELECT pe FROM ParticipantEntity pe where pe.eventId = :eventId