views:

61

answers:

3

How do you define a field, ie email as having an index using JPA annotations. We need a non-unique key on email because there are literally millions of queries on this field per day, and its a bit slow without the key.

@Entity
@Table(name="person", 
       uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"}))
public class Person {
    // Unique on code and uid
    public String code;
    public String uid;

    public String username;
    public String name;
    public String email;
}

I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.

+3  A: 

As fas as I know, there isn't a cross-JPA-Provider way to specify indexes. However, you can always create them by hand directly in the database, most DBs will pick them up automatically during query planning.

Tassos Bassoukos
lol, thats assuming you have DBA's that do the job of a DBA (:
Jacob
I find it slightly odd that there is a way to do "unique" but not a way to do an index.
Jacob
@Jacob - Well it is important to know at the application level whether some field will be unique or not. Indexes, on the other hand, are for the purposes of optimizing the db access. There is no need (as far as I see) to know whether a column is an index or not at the java layer. Like you said, the DBA can set up an index if it seems that a particular column would benefit from it.
Java Drinker
@Jacob, there's no Index suport because that is simply an optimization (usually an important one, but still an optimization). OTOH if a field (or set of fields) is unique or not depends on the model, and will affect correctness. Also, no need for a fully-fledged 200USD/Hr DBA, some simple index creation statements usually suffice.
Tassos Bassoukos
+2  A: 

It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.

Thierry-Dimitri Roy
+3  A: 

I'd really like to be able to specify database indexes in a standardized way but, sadly, this is not part of the JPA specification (maybe because DDL generation support is not required by the JPA specification, which is a kind of road block for such a feature).

So you'll have to rely on a provider specific extension for that. Hibernate, OpenJPA clearly do offer such an extension. I can't confirm for DataNucleus but since indexes definition is part of JDO, I guess it does.

I really hope index support will get standardized in next versions of the specification and thus somehow disagree with other answers, I don't see any good reason to not include such a thing in JPA (especially since the database is not always under your control) for optimal DDL generation support.

By the way, I suggest downloading the JPA 2.0 spec.

Pascal Thivent