【问题标题】:Does Hibernate automatically create index?Hibernate 会自动创建索引吗?
【发布时间】:2016-07-17 22:06:03
【问题描述】:

我有一个超过 500 万行的表 Term。每行由一个 ID 和一个“名称”组成。使用“名称”字段进行搜索大约需要 35 秒。

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

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注解:

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

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

在“名称”字段上搜索太慢了,所以我猜没有索引。 Hibernate 会自动在此表中的 id 和 name 上创建索引吗?如果没有,如何让它为两者创建索引?

【问题讨论】:

    标签: mysql hibernate


    【解决方案1】:

    使用@Index注解:

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

    Hibernate 会在启动时创建表时自动创建索引。

    【讨论】:

    • 我需要在 columnList 中添加 'id' 吗?否则主键 'id' 将被自动编入索引。
    • 为什么只有一个name="name_idx"?索引“id”需要另一个名称吗?
    • 在多个列上有一个索引,这就是我的代码所说的(我从我们的生产代码库中获取它,所以我知道它是正确的)。
    • 谢谢。它如何用于多列上的单个索引?
    • 谢谢。很高兴知道。
    【解决方案2】:

    主键是自动索引的,对于name字段,你要加一个@Index注解:

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

    【讨论】:

      猜你喜欢
      • 2021-06-03
      • 2010-10-24
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2018-11-19
      • 2011-05-29
      相关资源
      最近更新 更多