How to create indexes on multiple columns

谁说胖子不能爱 提交于 2020-02-15 13:48:11

问题


We have the following entity relationships where a User belongs to a particular Organization. My queries either look like "select * from User where org=:org" or "select * from User where org=:org and type=:type"

I have separate indexes on the User class. The first query will be fine, because of the Index on the foreign key element. Does the second query mandate a multi columnindex on org and type columns. If so how should I annotate to create one such index.

@Entity 
class User {
...

@ManyToOne 
@ForeignKey
@Index
Organization org;

@Index
Type type;    
...
}

回答1:


This is doable using the Hibernate specific @Table annotation. From the documentation:

2.4.1 Entity

...

@Table(appliesTo="tableName", indexes = { @Index( name="index1", columnNames={"column1", "column2"} ) } ) creates the defined indexes on the columns of table tableName. This can be applied on the primary table or any secondary table. The @Tables annotation allows your to apply indexes on different tables. This annotation is expected where @javax.persistence.Table or @javax.persistence.SecondaryTable(s) occurs.

Reference

  • Hibernate Annotations Reference Guide
    • 2.4. Hibernate Annotation Extensions



回答2:


As you can read in JSR-000338 Java Persistence 2.1 Proposed Final Draft Specification:

11.1.23 Index Annotation

The Index annotation is used in schema generation. Note that it is not necessary to specify an index for a primary key, as the primary key index will be created automatically, however, the Index annotation may be used to specify the ordering of the columns in the index for the primary key.

@Target({}) @Retention(RUNTIME)
public @interface Index {
  String name() default "";
  String columnList();
  boolean unique() default false;
}

The syntax of the columnList element is a column_list, as follows:

column::= index_column [,index_column]*
index_column::= column_name [ASC | DESC]

The persistence provider must observe the specified ordering of the columns.

If ASC or DESC is not specified, ASC (ascending order) is assumed.

Usage example:

@Table(indexes = {
        @Index(columnList = "org,type"),
        @Index(columnList = "another_column")})



回答3:


Yes, it is possible using JPA 2.1 as seen in the specification here:

http://download.oracle.com/otndocs/jcp/persistence-2_1-pfd-spec/index.html

on page 445 it states that

The Index annotation is used in schema generation

columnList (Required) The names of the columns to be included in the index.

An example of usage can be seen here:

http://java-persistence-performance.blogspot.co.uk/2013/03/but-what-if-im-not-querying-by-id.html

It seems that the syntax is the same or very similar to Hibernate.



来源:https://stackoverflow.com/questions/3725545/how-to-create-indexes-on-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!