Jump to: navigation, search

EclipseLink/Examples/JPA/Indexes


EclipseLink (as of 2.2) provides a way to have a database INDEX generated when EclipseLink is used to generate the database. An index is used in a database to optimize queries that use that column to provide optimal look-up and avoid table scans. Different databases have different levels of index support, EclipseLink supports the creation of basic indexes on databases that support them. Normally database auto-index primary key and foreign key fields, so normally these do not require indexes.

EclipseLink supports index creation using its @Index annotation or <index> xml element. The @Index has a name, schema, catalog, table, unique and a set of column names. An @Index can be put on any @Basic attribute and all of its properties will be defaulted to index the attribute's column. @Index can be set on a class to define a multi-column index. The @Indexes annotation can be used to define multiple indexes in one class.

Example Index

The firstName and lastName are indexed, together and individually.

@Entity
@Index(name="EMP_NAME_INDEX", columns={"F_NAME","L_NAME"})
public class Employee{
    @Id
    private long id;
    @Index
    @Column(name="F_NAME")
    private String firstName;
    @Index
    @Column(name="L_NAME")
    private String lastName;
    ...
}

This produces the SQL,

CREATE INDEX INDEX_EMPLOYEE_F_NAME ON EMPLOYEE (F_NAME)
CREATE INDEX INDEX_EMPLOYEE_L_NAME ON EMPLOYEE (L_NAME)
CREATE INDEX EMP_NAME_INDEX ON EMPLOYEE (F_NAME, L_NAME)
</sql>