Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an annotation to define a multi column index in jpa2

Hibernate provides a mechanism to define multi column indexes via the Table. Is there a way to specify this is an ORM agnostic fashion via JPA or JPA2 (e.g. using the javax.persistence.* APIs)

like image 501
user339108 Avatar asked Sep 20 '10 09:09

user339108


2 Answers

Just came about the very same issue using Hibernate 4.3.8 with JPA 2.1 integration. It seems, mjaggard's answer is correct. However, the given example of usage looks like this:

@Index(name="EMP_NAME_INDEX", columnList={"F_NAME", "L_NAME"})

I don't know if this ever worked. I do know that in my case with JPA 2.1 the value of columnList is not an array but a String. So for me, the desired two-column index can be defined in the following way:

@Index(name="EMP_NAME_INDEX", columnList="F_NAME,L_NAME")

That is, just use a comma to separate the column names in a single string. This worked for me using a Postgres DBMS. I checked back and the index was successfully created over both columns.

like image 192
khituras Avatar answered Nov 10 '22 00:11

khituras


It's possible to declare multi-column index in JPA 2.1 Here is a sample Entity class that demonstrates multi-column indexing.

@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames={"product_id","store_id"}))
class MyEntity {
    @Column(name="product_id")
    private String productId;

    @Column(name="store_id")
    private Long storeId;
}

Please note that columnNames must be the name of the columns in DB, not the attribute name.

like image 33
Nayan Avatar answered Nov 09 '22 23:11

Nayan