如何使用Hibernate for PostgreSQL创建索引

问题描述 投票:4回答:2

我正在开发一个Spring-MVC应用程序,我在其中使用Hibernate作为PostgreSQL的ORM工具。对于项目模型中的一些实体,我想创建索引以加快查找速度。在我阅读时,我发现可以使用Hibernate创建索引。不幸的是,我没有太多运气。我只尝试在一个Model类上创建它,但是当我检入PGAdmin时,我看不到该表的任何索引。

当我尝试将@Index参数提供给@Table注释时,我收到错误。任何人都可以告诉我如何通过Hibernate对列和整个表进行自动索引注释。非常感谢。

在线用户模型://这个我刚刚用于测试的类

import org.hibernate.search.annotations.Indexed;

import javax.persistence.*;
@Entity
@Table(name="onlineusers" )
@Indexed(index = "onlineuserindex")
public class OnlineUsers {

  @Id
    @Column(name="onlineuserid")
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "online_gen")
    @SequenceGenerator(name = "online_gen",sequenceName = "online_seq")
    private int onlineUserId;


    @Column(name = "onlineusername")
    private String personName;
}

请注意,当我尝试以下内容时:

@Indexed(index = "usernameindex");
@Column(name="username");
private String userName;

我收到错误,@ Index不适用于某个字段。

POM.hml:

 <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>4.0.6.RELEASE </org.springframework-version>
        <org.aspectj-version>1.7.4</org.aspectj-version>
        <org.slf4j-version>1.7.5</org.slf4j-version>
        <hibernate.version>4.3.9.Final</hibernate.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

  <!-- Hibernate search dependencies -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-search-orm</artifactId>
            <version>5.2.0.Final</version>
        </dependency>

    <!--    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
-->

请让我知道我做错了什么。非常感谢。 :-)

java spring hibernate postgresql hibernate-mapping
2个回答
2
投票

来自@IndexedHibernate Search注释仅适用于类型。所以你不能在属性上使用它们。

阅读你的问题,似乎你想在表中添加一个数据库索引?若然后你必须使用Index Annotation


3
投票

您可以使用@Index JPA注释:

@Entity
@Table(name = "onlineusers",
    indexes = {
        @Index(name = "usernameindex",  columnList="username", unique = true)   
    }
)
public class OnlineUsers {
   ...
}

仅在使用自动hbmddl模式生成时才应用此选项。如果数据库模式是在外部生成的(例如,在使用Flyway时),则此注释将不起任何作用。

将数据库模式生成委派给外部进程(数据库迁移工具或手动脚本更新过程)时,需要在迁移脚本中包含索引。

因此,您要么使用Hibernate生成整个模式(not even recommended for production systems),要么依赖数据库迁移框架(例如Flyway),索引只包含在增量模式更新脚本中。

© www.soinside.com 2019 - 2024. All rights reserved.