EJB 查找方法和多个标识符

EJB find method and multiple identifiers

我有以下包含多个@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

}

需要实现查找方法:

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

这段代码有什么问题?

您需要使用 @EmbeddedId class.

定义您的实体

因此您的原始实体将具有:

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

    @EmbeddedId
    private MetaTableEntPK pk;

    ... etc

您的可嵌入 class 将是:

@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,比如说。例如,以下查询将找到具有特定 dataInd 的所有 MetaTableEnt 个对象:

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

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