EJB查找方法和多个标识符

时间:2015-05-25 05:04:41

标签: java-ee ejb

我有以下包含多个@Id的实体bean:

@Entity
@Table (name="meta_tables")
public class MetaTableEnt implements Serializable{

    @Id     
    @Column(name="data_ind")
    private Integer dataInd;

    @Id     
    @Column(name="sk")
    private Integer sk;

    // other columns

}

需要实现find方法:

MetaTableEnt mte = em.find(MetaTableEnt.class, object);

我将对象定义如下,但这不起作用:

public class MetaTableKey implements Serializable {
    public int dbInd;
    public int sk;
}

MetaTableKey object = new MetaTableKey();
object.dbInd = dbInd;
object.sk = sk;

我收到此错误消息:

Provided id of the wrong type for class bi.metadata.MetaTableEnt. Expected: class bi.metadata.MetaTableEnt, got class bi.metadata.MetaTableDao$MetaTableKey

这段代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

您需要使用@EmbeddedId类定义您的实体。

所以你原来的实体会有:

@Entity
@Table (name="meta_tables")
public class MetaTableEnt implements Serializable {

    @EmbeddedId
    private MetaTableEntPK pk;

    ... etc

你的可嵌入课程将是:

@Embeddable
public class MetaTableEntPK implements Serializable {

    @Column(name="data_ind")
    private Integer dataInd;

    @Column(name="sk")
    private Integer sk;

    public MetaTableEntPK(Integer dataInd, Integer sk) {
        this.dataInd = dataInd;
        this.sk = sk;
    }
}

然后你的查找代码将是:

MetaTableEntPK pk = new MetaTableEntPK(1, 2);
MetaTableEnt mte = em.find(MetaTableEnt.class, pk);

注意:在JPQL查询中,您需要将此PK中的字段称为pk.dataInd。例如,以下查询将查找具有特定MetaTableEnt的所有dataInd个对象:

SELECT object(x) FROM MetaTableEnt x WHERE x.pk.dataInd = 1

顺便说一句,不要听JB Nizet。我们的400多个实体中有130个使用这些@Embeddable密钥,并且没有什么特别困难。