3.6.6.2. Typing and Ordering

When loading data into a field, OpenJPA examines the value you assign the field in your declaration code or in your no-args constructor. If the field value’s type is more specific than the field’s declared type, OpenJPA uses the value type to hold the loaded data. OpenJPA also uses the comparator you’ve initialized the field with, if any. Therefore, you can use custom comparators on your persistent field simply by setting up the comparator and using it in your field’s initial value.

Example 84. Using Initial Field Values

Though the annotations are left out for simplicity, assume employeesBySal and departments are persistent fields in the class below.

public class Company {

    // OpenJPA will detect the custom comparator in the initial field value
    // and use it whenever loading data from the database into this field
    private Collection employeesBySal = new TreeSet(new SalaryComparator());
    private Map departments;

    public Company {
        // or we can initialize fields in our no-args constructor; even though
        // this field is declared type Map, OpenJPA will detect that it's
        // actually a TreeMap and use natural ordering for loaded data
        departments = new TreeMap();
    }

    // rest of class definition...
}