具有PK实体的JPA NamedQueries

时间:2011-01-20 17:29:34

标签: orm jpa

我使用Netbeans生成了实体类。 我的类有一个复合主键,因此Netbeans为我生成了一个额外的PK实体类。 我希望在Entity类中使用NamedQuery但是作为我传递给命名查询的参数是嵌入在PK类中,NamedQuery调用失败并且查询似乎不完整。

任何人都可以提供一个示例,说明我的代码应该使用具有复合PK(@EmbeddedId关联)的NamedQuery吗?以下失败:

门面类(部分):

@Stateless
public class EMyEntityFacade extends AbstractFacade<EMyEntity> {

public EMyEntityFacade() {
    super(EMyEntity.class);
}

//does not work
/*
private Query queryByComp1Id(int comp1Id) {
    Query query = this.getEntityManager().createNamedQuery("EMyEntity.findByComp1Id");
    query.setParameter("comp1Id", comp1Id);
    return query;
}
*/

//any nearer?
private Query queryByComp1d(int comp1Id) {
    EMyEntityPK eMyEntityPK = new EMyEntityPK();

    Query query = this.getEntityManager().createNamedQuery("EMyEntity.findByComp1Id");

    eMyEntityPK.setComp1Id(comp1Id);

    //how do I pass the eMyEntityPK through to the Entity so the query is well formed? 
    //???

    return query;
}

public List<EMyEntity> findByComp1Id(int comp1Id) {
    Query query = queryByComp1Id(comp1Id);
    return query.getResultList();
}

实体类(部分):

@Entity
@Table(name = "my_entity")
@NamedQueries({
    @NamedQuery(name = "EMyEntity.findByComp1Id",
    query = "SELECT e FROM EMyEntity e WHERE e.eMyEntityPK.comp1Id = :comp1Id"),...)})

public class EMyEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected EMyEntityPK eMyEntityPK;
    @Basic(optional = false)
    @Column(name = "inherit_from_parent")
    ...
    ...
}

PK Class(part):

@Embeddable
public class EMyEntityPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "comp1_id")
    private int comp1Id;
    @Basic(optional = false)
    @Column(name = "comp2_id")
    private int comp2Id;
    ...
    ...
}

1 个答案:

答案 0 :(得分:1)

您应该传递表示主键的who对象,而不仅仅是其中的一个字段。如果你需要查询部分pk,请在where子句中详细说明:where pk.fld=