JPA 2 - Using @ElementCollection in CriteriaQuery

@Entity public class Person { @ElementCollection private List<Location> locations; [...] } @Embeddable public class Location { private Integer dummy; private Date creationDate; [...] } 

Given the following structure, I would like to execute the HQL or CriteriaQuery equivalent of the following SQL:

 SELECT l.* FROM Location l INNER JOIN Person p ON (p.id = l.person_id) WHERE p.id = ? AND l.creationDate > ? 

I want to return a list of locations that are associated with this person and whose creation of dates after this.

Thanks in advance!

Mark

Edit ***: I edited SQL as it was something of a fallacy. I do not want to request seats independently.

+7
java orm jpa criteria-api
source share
2 answers

This is not possible; you cannot request an Embeddable . From JPA Wikibook:

Inline Collections

An An ElementCollection can be used to define a set of Embeddable objects. This is not a typical use of Embeddable objects since objects are not embedded in the original object table, but are stored in a separate collection table. This is similar to a OneToMany , except the target is Embeddable instead of Entity . This allows a collection of simple objects to be easily identified without requiring simple objects to define Id or ManyToOne reverse mapping. ElementCollection can also cancel mappings or tables for their collection, so you can have multiple objects reference the same inline class, but each stores their dependent objects in a separate table.

Limitations of using ElementCollection instead of OneToMany is that the target objects cannot be requested , saved, merged regardless of their parent object. They are strictly private (dependent) objects, just like an Embedded mapping. There is no ElementCollection on the cascading option; the target objects are always saved, merged, deleted with their parents. ElementCollection can still use the selection type and defaults to LAZY just like other collection mappings.

To achieve what you want, use OneToMany and Entity instead of ElementCollection and Embeddable . Or change your approach and request Person .

+14
source share

Pascal's key phrase

target objects cannot be requested, saved, combined regardless of their parent

Since you are dependent on the parent object, you should do this using something like ...

SELECT p FROM PERSON, IN (p.locations) WHERE p.id = ?1 AND locations = ?2

(Based on the answer Execute the "MEMBER" request from the "ElementCollection" fields in JP-QL (JPA 2.0) - this is actually a @ElementCollection map, to which I was looking for the answer!)

+2
source share

All Articles