Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Hibernate automatically create index?

I have a table Term with a little more than 5 million rows. Each row consists of an ID and a "name". A search with "name" field takes nearly 35 seconds.

MariaDB [WordDS]> select * from Term where name="Google";
+---------+--------+
| id      | name   |
+---------+--------+
| 1092923 | Google |
+---------+--------+
1 row in set (35.35 sec)

The script from the table generated by Hibernate:

DROP TABLE IF EXISTS `Term`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Term` (
  `id` bigint(20) NOT NULL,
  `name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

Java annotation:

@Id
@Column(unique=true)
private long id;

@NotNull
@Size(min = 1, max = 100)
private String name;

It's so slow to search on the field "name", so I guess there is no index. Does Hibernate automatically create index on id and name in this table? If not, how to let it create index for both?

like image 390
user697911 Avatar asked Mar 30 '16 04:03

user697911


People also ask

Does hibernate use index?

By default, Hibernate Search will use the fully qualified class name as the index name. With the @Entity annotation from JPA, we map a class to a database table and, its fields to the table columns.

Can indexes be created automatically?

A Unique index will be created automatically when you define a PRIMARY KEY or UNIQUE KEY constraints on the specified columns.

Which constraint will create an index automatically?

PRIMARY KEY or UNIQUE constraint When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index. The primary key column cannot allow NULL values.

Is index automatically created on primary key?

Yes, primary key is automatically indexed in MySQL because primary key, index, etc gets stored into B-trees. All engines including InnoDB as well as MyISAM automatically supports the primary key to be indexed. The primary key is implicitly indexed in InnoDB, MyISAM, and other engines.


2 Answers

Use the @Index annotation:

@Entity
@Table(name = "Term", indexes = {
    @Index(columnList = "name, id", name = "name_idx") })

Hibernate will create the index automatically when it creates the table at startup.

like image 200
Tim Biegeleisen Avatar answered Oct 21 '22 11:10

Tim Biegeleisen


The primary key is indexed automatically, for the name field, you have to add an @Index annotation:

@NotNull
@Size(min = 1, max = 100)
@Index(name = "idx_name")
private String name;
like image 1
Robby Cornelissen Avatar answered Oct 21 '22 10:10

Robby Cornelissen