简体   繁体   English

JPA:使用抽象类查询OneToOne关系

[英]JPA: Querying a OneToOne relationship with an abstract class

I have two classes which have a unidirectional OneToOne relationship: 我有两个具有单向OneToOne关系的类:

@Entity
@Table(name = "TypeA")
public class TypeA implements A
{
    ...
}

@Entity
@Table(name = "OTHER")
public class Other
{
    @OneToOne
    private A a;

    .....
}

When I save these classes everything works fine. 当我保存这些类时,一切正常。 Now I want to retrieve the Other based on an existing A. I created a CriteriaQuery which basically says "SELECT * FROM OTHERE WHERE a = :a". 现在,我想基于现有的A检索Other。我创建了一个CriteriaQuery,它基本上说“ SELECT * FROM OTHERE WHERE a =:a”。 But when I set an object of type A into the query it will fail. 但是,当我在查询中设置类型为A的对象时,它将失败。 Looking into the database I can see that the OTHER.A field is actually a varchar with the value "typeA:123" (where 123 is the ID of the A-object). 查看数据库,我可以看到OTHER.A字段实际上是具有值“ typeA:123”(其中123是A对象的ID)的varchar。 Unfortunately I can't use a bidirectional mapping here. 不幸的是,我不能在这里使用双向映射。

    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Other> cq = criteriaBuilder.createQuery(Other.class);
    final Root<Other> root = cq.from(Other.class);
    cq.where(cb.equal(root.get(Other_.a), myActualAObject));
    final TypedQuery<Other> tq = em.createQuery(cq);
    final Other other = tq.getSingleResult();

Any ideas how to perform the query mentioned above? 任何想法如何执行上述查询?

Thanks in advance. 提前致谢。

Cheers Philipp 干杯菲利普

A is an interface, not an entity, so I don't think a standard OneToOne mapping will work without using provider specific code - JPA only allows mapping to JPA objects, not interfaces. A是接口,而不是实体,因此,我认为标准的OneToOne映射在不使用提供程序特定代码的情况下不会起作用-JPA仅允许映射到JPA对象,而不是接口。 For this to work, you need to specify the target type in the mapping so it knows 'a' can only be TypeA entity instances. 为此,您需要在映射中指定目标类型,以便知道“ a”只能是TypeA实体实例。 Or you can just change the type from A to TypeA. 或者,您可以将类型从A更改为TypeA。

EclipseLink has a variable OneToOne mapping concept used to map interfaces here: http://eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_variableonetoone.htm EclipseLink具有可变的OneToOne映射概念,用于在此处映射接口: http : //eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_variableonetoone.htm

I'm not sure what other providers have that is equivalent. 我不确定其他提供者的服务是否等同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM