使用 JPA 指定索引(非唯一键) [英] Specifying an Index (Non-Unique Key) Using JPA

查看:37
本文介绍了使用 JPA 指定索引(非唯一键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何定义一个字段,例如 email 作为使用 JPA 注释的索引.我们需要在 email 上使用一个非唯一键,因为每天在这个字段上有数百万次查询,如果没有键,它会有点慢.

How do you define a field, eg email as having an index using JPA annotations. We need a non-unique key on email because there are literally millions of queries on this field per day, and its a bit slow without the key.

@Entity
@Table(name="person", 
       uniqueConstraints=@UniqueConstraint(columnNames={"code", "uid"}))
public class Person {
    // Unique on code and uid
    public String code;
    public String uid;

    public String username;
    public String name;
    public String email;
}

我看到了一个特定于 Hibernate 的注释,但我试图避免供应商特定的解决方案,因为我们仍在 Hibernate 和 datanucleus 之间做出决定.

I have seen a hibernate specific annotation but I am trying to avoid vendor specific solutions as we are still deciding between hibernate and datanucleus.

更新:

从 JPA 2.1 开始,您可以执行此操作.请参阅:此位置不允许使用注释@Index

As of JPA 2.1, you can do this. See: The annotation @Index is disallowed for this location

推荐答案

使用 JPA 2.1,您应该能够做到.

With JPA 2.1 you should be able to do it.

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Index;
import javax.persistence.Table;

@Entity
@Table(name = "region",
       indexes = {@Index(name = "my_index_name",  columnList="iso_code", unique = true),
                  @Index(name = "my_index_name2", columnList="name",     unique = false)})
public class Region{

    @Column(name = "iso_code", nullable = false)
    private String isoCode;

    @Column(name = "name", nullable = false)
    private String name;

} 

更新:如果您需要使用两列或更多列创建和索引,您可以使用逗号.例如:

Update: If you ever need to create and index with two or more columns you may use commas. For example:

@Entity
@Table(name    = "company__activity", 
       indexes = {@Index(name = "i_company_activity", columnList = "activity_id,company_id")})
public class CompanyActivity{

这篇关于使用 JPA 指定索引(非唯一键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆