Reputation: 1
I have three classes: A.java, B.java and C.java. A and B extend C. How do I write a JPA query to works correctly? I tried
Query query = em.createQuery("select c from C c left join A a left join B b where (c.id = a.id or c.id = b.id)");
Upvotes: 0
Views: 595
Reputation: 11551
The short answer is that you don't. In JPA:
The default strategy, InheritanceType.SINGLE_TABLE, is used if the @Inheritance annotation is not specified on the root class of the entity hierarchy
When you select everything from table C, the JPA provider will instantiate classes based on the discriminator column
, so
List<C> rl = em.createQuery("select c from C c", C.class).getResultList();
System.out.println(rl);
will give you:
Hibernate: select c0_.id as id2_0_, c0_.DTYPE as DTYPE1_0_ from C c0
[model.C@2cac4385, model.A@6731787b, model.B@16f7b4af]
If you need to you can use the instanceof
operator in Java to determine the result types. If you want a specific subclass, then just query it:
List<A> rl = em.createQuery("select a from A a", A.class).getResultList();
System.out.println(rl);
which will give you:
Hibernate: select a0_.id as id2_0_ from C a0_ where a0_.DTYPE='A'
[model.A@3fc9dfc5]
Reference: Entity Inheritance
Upvotes: 1