Jump to: navigation, search

Difference between revisions of "EclipseLink/Examples/JPA/MappingSelectionCriteria"

m (Example of Expression criteria relationship)
Line 38: Line 38:
 
         ExpressionBuilder builder = new ExpressionBuilder();
 
         ExpressionBuilder builder = new ExpressionBuilder();
 
         mapping.setSelectionCriteria(builder.getField("EMPLOYEE.DEPT_ID").equal(builder.getParameter("DEPARTMENT.DEPT_ID").
 
         mapping.setSelectionCriteria(builder.getField("EMPLOYEE.DEPT_ID").equal(builder.getParameter("DEPARTMENT.DEPT_ID").
                and(build.getField("EMPLOYEE.POSITION").equal("MANAGER"));
+
        and(builder.getField("EMPLOYEE.POSITION").equal("MANAGER"));
 
     }
 
     }
 
}
 
}
 
</source>
 
</source>

Revision as of 15:26, 13 August 2009

Normally in the database a relationship is defined through a foreign key, either from the source table to the target table (ManyToOne), or from the target table to the source table (OneToMany). However, sometimes a relationship is more complex, and involves a comparison or computation. The JPA specification only allows relationships to be defines using foreign keys (JoinColumn), but EclipseLink also provides and extended Expression criteria API to allow complex relationships to be defined.

Consider a Department that has a "manager" relationship to Employee. Instead of having a foreign key to its manager, the Employee has a foreign key to its Department, and an additional field that defines the Employee's position. EclipseLink does not currently define an annotation to define an Expression relationship so a DescriptorCustomizer can be used.

Example of Expression criteria relationship

@Entity
@Customizer(org.acme.persistence.DepartmentCustomizer.class)
public class Department {
    @Id
    private long id;
    @OneToOne
    private Employee manager;
    @OneToMany(mappedBy="department")
    private List<Employee> employees;
    ...
}
@Entity
public class Employee {
    @Id
    private long id;
    @ManyToOne
    @JoinColumn(name="DEPT_ID")
    private Department department;
}
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.expressions.*;
import org.eclipse.persistence.mappings.OneToOneMapping;
 
public class DepartmentCustomizer implements DescriptorCustomizer {
    public void customizer(ClassDescriptor descriptor) {
        OneToOneMapping mapping = (OneToOneMapping)descriptor.getMappingForAttributeName("manager");
        ExpressionBuilder builder = new ExpressionBuilder();
        mapping.setSelectionCriteria(builder.getField("EMPLOYEE.DEPT_ID").equal(builder.getParameter("DEPARTMENT.DEPT_ID").
        and(builder.getField("EMPLOYEE.POSITION").equal("MANAGER"));
    }
}