views:

30

answers:

2

Colleagues, Using JPA I need resolve following issue: at database level exits 3 entities (saying SuperEntity, DetailsAEntity and DetailsBEntity). SuperEntity contains common part of fields for DetailsAEntity and DetailsBEntity.

So the question: is it possible to resolve collection of mixed elements DetailsAEntity and DetailsBEntity from JPA? May be exits some extension in toplink to specify class for entity?

+2  A: 

Assuming SuperEntity is mapped as the root of the inheritance tree then the result of queries for this type can return a heterogeneous collection of its concrete subclasses.

Doug Clarke
Yes, thanks! It works.
Dewfy
A: 

Queries are polymorphic in standard JPA. Here are the relevant sections from the JPA 1.0 Specification:

3.6.5 Polymorphic Queries

By default, all queries are polymorphic. That is, the FROM clause of a query designates not only instances of the specific entity class(es) to which it explicitly refers, but subclasses as well. The instances returned by a query include instances of the subclasses that satisfy the query conditions.

For example, the query

select avg(e.salary) from Employee e where e.salary > 80000

returns the average salary of all employees, including subtypes of Employee, such as Manager and Exempt.

And

4.4.8 Polymorphism

Java Persistence queries are automatically polymorphic. The FROM clause of a query designates not only instances of the specific entity class(es) to which explicitly refers but of subclasses as well. The instances returned by a query include instances of the subclasses that satisfy the query criteria.

So any query on a supertype will include subtypes in the results by default.

Pascal Thivent
@Pascal It is clear, but is not an answer to my question. I didn't ask if it possible, I have asked how to do it. Copypaste of spec "The instances returned by a query include instances of the subclasses that satisfy the query criteria" - doesn't shows me how to do it. avg - retursn number, but i need 2 types of objects in the collection
Dewfy
@Dewfy I'm sorry if you didn't find it helpful but I think it does answer the question (just do a query on a type) and the spec even provides an example (*returns the average salary of all employees, including subtypes of Employee, such as Manager and Exempt*). This also clarifies that this is standard JPA, which was my main goal. If you don't find it helpful, maybe other readers will.
Pascal Thivent