JPA查询多对一关联

时间:2010-04-11 18:53:49

标签: jpa object field associations

我想构建以下伪查询

Select a From APDU a where a.group.id= :id

group是APDUGroup.class类型的APDU类中的字段。

我只想根据APDUGroup的id获取APDU列表。

如何使用标准JPA查询?

更新

是的,我已尝试过上述查询,并在发布S / O之前尝试了几个小时的其他变体。以下是上面查询生成的SQL:

SELECT t1.ID, t1.status, t1.type, t1.modified, t1.response, t1.expectedSize, t1.created, t1.description, t1.sequence, t1.name, t1.command, t1.recurring, t1.auth, t1.createdBy, t1.APDUGroup, t1.modifiedBy FROM APDUGroup t0, APDU t1 WHERE ((t0.ID = ?) AND (t0.ID = t1.APDUGroup))

查询看起来没问题但是从我的表中没有选择任何内容。 在我的测试数据库中,至少有100个APDU,APDUGroup = 1。

我正在使用eclipselink作为JPA提供商。

1 个答案:

答案 0 :(得分:4)

鉴于以下实体:

@Entity
public class APDU implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private APDUGroup group;

    //...

}

@Entity
public class APDUGroup implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    //...
}

以下查询将返回给定APDUGroup id的APDU列表:

select a from APDU a where a.group.id = :id

哦,等等,这是你的疑问:)