java – 如何在hibernate实体中通过几列定义索引?

前端之家收集整理的这篇文章主要介绍了java – 如何在hibernate实体中通过几列定义索引?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
早上.

我需要在hibernate实体中添加索引.据我所知,可以使用@Index注释来指定单独列的索引,但我需要一个实体的几个字段的索引.

我用谷歌搜索并找到了jboss注释@Table,它允许这样做(按照规范).但是(我不知道为什么)这个功能不起作用.可能是jboss版本低于必要,或者我可能不明白如何使用这个注释,但是…复杂索引没有创建.

为什么不能创建索引?

jboss版本4.2.3.GA

实体示例:

  1. package somepackage;
  2. import org.hibernate.annotations.Index;
  3.  
  4. import javax.persistence.Column;
  5. import javax.persistence.Entity;
  6. import javax.persistence.GeneratedValue;
  7. import javax.persistence.Id;
  8.  
  9. @Entity
  10. @org.hibernate.annotations.Table(appliesTo = House.TABLE_NAME,indexes = {
  11. @Index(name = "IDX_XDN_DFN",columnNames = {House.XDN,House.DFN}
  12. )
  13. }
  14. )
  15.  
  16. public class House {
  17. public final static String TABLE_NAME = "house";
  18. public final static String XDN = "xdn";
  19. public final static String DFN = "dfn";
  20.  
  21. @Id
  22. @GeneratedValue
  23. private long Id;
  24.  
  25. @Column(name = XDN)
  26. private long xdn;
  27.  
  28. @Column(name = DFN)
  29. private long dfn;
  30.  
  31. @Column
  32. private String address;
  33.  
  34. public long getId() {
  35. return Id;
  36. }
  37.  
  38. public void setId(long id) {
  39. this.Id = id;
  40. }
  41.  
  42. public long getXdn() {
  43. return xdn;
  44. }
  45.  
  46. public void setXdn(long xdn) {
  47. this.xdn = xdn;
  48. }
  49.  
  50. public long getDfn() {
  51. return dfn;
  52. }
  53.  
  54. public void setDfn(long dfn) {
  55. this.dfn = dfn;
  56. }
  57.  
  58. public String getAddress() {
  59. return address;
  60. }
  61.  
  62. public void setAddress(String address) {
  63. this.address = address;
  64. }
  65. }

当jboss / hibernate尝试创建表“house”时,它抛出以下异常:

  1. Reason: org.hibernate.AnnotationException: @org.hibernate.annotations.Table references an unknown table: house

解决方法

请尝试以下方法
  1. @Entity
  2. @org.hibernate.annotations.Table(appliesTo = House.TABLE_NAME,House.DFN}
  3. )
  4. }
  5. )
  6. @Table(name="house")
  7. public class House {
  8. ...
  9. }

请注意,这还应该允许您创建多列索引(基于索引名称):

  1. @Index(name = "index1")
  2. public String getFoo();
  3.  
  4. @Index(name = "index1")
  5. public String getBar();

P.S.:您使用什么版本的Hibernate BTW?什么数据库/方言?

猜你在找的Java相关文章