简体   繁体   中英

JPA: Querying a OneToOne relationship with an abstract class

I have two classes which have a unidirectional OneToOne relationship:

@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". But when I set an object of type A into the query it will fail. 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). 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. For this to work, you need to specify the target type in the mapping so it knows 'a' can only be TypeA entity instances. Or you can just change the type from A to 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

I'm not sure what other providers have that is equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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