Difference between revisions of "EclipseLink/UserGuide/JPA/Basic JPA Development/Querying/Query Keys"

From Eclipsepedia

Jump to: navigation, search
m
 
Line 44: Line 44:
 
{{EclipseLink_JPA
 
{{EclipseLink_JPA
 
|previous= [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Batch Reading|Batch Reading]]
 
|previous= [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Batch Reading|Batch Reading]]
|next=    [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying/Support for Native Database Functions|Support for Native Database Functions]]
+
|next=    [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Transactions|Transactions]]
 
|up=      [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying|Querying]]
 
|up=      [[EclipseLink/UserGuide/JPA/Basic_JPA_Development/Querying|Querying]]
 
|version=2.2.0 DRAFT}}
 
|version=2.2.0 DRAFT}}

Latest revision as of 13:18, 17 April 2012

EclipseLink JPA

link="http://wiki.eclipse.org/EclipseLink"
EclipseLink
Website
Download
Community
Mailing ListForumsIRC
Bugzilla
Open
Help Wanted
Bug Day
Contribute
Browse Source


[edit] Query Keys in Queries

As of EclipseLink 2.1, it is possible to reference manually-defined query keys within JPA queries. Prior to this release, such query keys could only be referenced in native queries using expressions.

By default, EclipseLink creates query keys for all mapped attributes, but in some scenarios you may find it beneficial to add your own.

The following example shows...

public class EmployeeCustomizer implements DescriptorCustomizer {
 
    @Override
    public void customize(ClassDescriptor descriptor) throws Exception {
        // Direct (basic) query for the Oracle DB's ROWID value
        descriptor.addDirectQueryKey("rowId", "ROWID");
 
        // 1:M query accessing all projects which have a M:1 teamLeader reference to this employee
        // this can also be used to allow querying of large collections not wanted mapped
        OneToManyQueryKey projectsQueryKey = new OneToManyQueryKey();
        projectsQueryKey.setName("leadProjects");
        projectsQueryKey.setReferenceClass(Project.class);
        ExpressionBuilder builder = new ExpressionBuilder();
        projectsQueryKey.setJoinCriteria(builder.getField("PROJECT.LEADER_ID").equal(builder.getParameter("EMPLOYEE.EMP_ID")));
        descriptor.addQueryKey(projectsQueryKey);
    }
 
}

Then the query key can be references in the query in the same way any mapped attribute is.

TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e WHERE e.leadProjects IS NOT EMPTY", Employee.class);
return query.getResultList();


Eclipselink-logo.gif
Version: 2.2.0 DRAFT
Other versions...