开发者

JPA NamedQueries with PK Entities

I have generated Entity Classes using Netbeans. My Class has a composite primary key so Netbean开发者_JS百科s generated an additional PK Entity Class for me. I wish to use a NamedQuery in the Entity class but as the param I am passing into the named query is Embedded in the PK class, the NamedQuery call is failing and the query does not seem to be complete.

Can anyone offer an example of what my code should look like to use a NamedQuery which has a composite PK (@EmbeddedId association) in it? The following fails:

Facade Class (part):

@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 Class (part):

@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;
    ...
    ...
}


You should pass the who object representing the primary key, not just one field of it. If you need to query for part of the pk, symply refer to it in the where clause :where pk.fld=

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜