hibernate:创建索引
我想在我的数据库中创建几个索引。 不幸的是,我们必须将持久性提供程序从EclipseLink更改为Hibernate,但是使用javax.persistence.Index的解决方案也不能解决Hibernate的问题。
这就是这个类的样子:
@Entity @Table(name = "my_shop") public class Shop extends BaseEntity { @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Calendar lastUpdate; }
这应该是javax.persistence的解决方案。*:
import javax.persistence.Index; import javax.persistence.Table; @Table(name = "my_shop", indexes = @Index(columnList = "lastupdate") )
不推荐使用Hibernate注释,因此必须有理由不使用这些注释:
import org.hibernate.annotations.Index; // deprecated import org.hibernate.annotations.Table; @Table(..., indexes = @Index(columnNames = "lastupdate") )
我使用Glassfish 3.1.2.2,PostgreSQL 9.1,JPA 2.1和hibernate-core 4.3.4.Final。 如果我查看数据库,则不会通过psql“\ d +”在特定字段上创建索引。
这就是我的persistence.xml的样子:
... ...
只有EclipseLink可以轻松处理:
import org.eclipse.persistence.annotations.Index; @Entity @Table(name = "my_shop") public class Shop extends BaseEntity { @Index @Temporal(TemporalType.TIMESTAMP) @Column(nullable = false) private Calendar lastUpdate; }
我在@Column和@Index中使用所有组合“lastupdate”,“lastUpdate”和其他“name”属性测试了给定的解决方案,但似乎没有任何效果。
希望有人可以帮助我,欢呼!
更新1
坦克你的帮助! 确实这个解决方案有效
@javax.persistence.Table(name = "my_shop") @Table(appliesTo = "my_shop" ,indexes = {@Index(columnNames = "name", name = "name"), @Index(columnNames = "lastupdate", name = "lastupdate")} )
但仍然是org.hibernate.annotations.Index;
被标记为已弃用。 那么使用它是否是好的做法? 如果没有替代方案,因为显然javax.persistence.Index
不起作用。
org.hibernate.annotations.Index;
适用于每一个值:创建,更新,… javax.persistence.Index
无关紧要“hibernate.hbm2ddl.auto”具有哪个值,不起作用。
我使用JPA 2.1与Hibernate 4.3和PostgreSQL 9.3。 我没有索引问题
hibernate-commons-annotations-4.0.4.Final.jar hibernate-core-4.3.1.Final.jar hibernate-jpa-2.1-api-1.0.0.Final.jar jandex-1.1.0.Final.jar javassist-3.18.1-GA.jar jboss-transaction-api_1.2_spec-1.0.0.Final.jar
虽然我的配置有
那是我的实体映射
import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; @Entity @Table(name = "users", indexes = { @Index(columnList = "id", name = "user_id_hidx"), @Index(columnList = "current_city", name = "cbplayer_current_city_hidx") })
PS。 事实上,我对这些注释有一些问题。 我不能为索引指定表空间,必须为SINGLE_TABLE层次结构的父类中的子类创建indecies。
使用Hibernate
您需要在@Index
注释中输入name
属性。
import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Table; @Entity @Table( indexes = { @Index(columnList = "description", name = "product_description") }) public class Product implements Serializable { // ... private String description; // getters and setters }
如果不需要EclipseLink
,它会自动创建name
。
@Index
注释仅适用于hibernate.hbm2ddl.auto=create-drop
,请参阅Hibernate论坛中的此条目 。
需要注意的是,此选项会删除表,但通常hibernate.hbm2ddl.auto
仅用于开发目的。
总结一下:
- JPA 2.1:
javax.persistence.Index
(参见JSR-000338 ,第450页,第11.1.23项) - Hibernate ORM :
org.hibernate.annotations.Index