標籤:
今天在做項目的時候,一個中間表沒有主鍵,所有在建立實體的時候也未加組件,結果報以下錯誤:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘hibernateSessionFactory‘ defined in class path resource [spring-config/ac-cif-srv-config.xml]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: XXX
可以看出,其指出某一類是未指定標識符的實體,其主要原因是hibernate在進行掃描實體的時候,為發現其主鍵標識。所以就在其類上添加主鍵標識。因為我的這個類比較特殊,需要添加聯合主鍵。
聯合主鍵用Hibernate註解映射方式主要有三種:
一、將聯合主鍵的欄位單獨放在一個類中,該類需要實現java.io.Serializable介面並重寫equals和hascode,再將該類註解為@Embeddable,最後在主類中(該類不包含聯合主鍵類中的欄位)儲存該聯合主鍵類的一個引用,並產生set和get方法,並將該引用註解為@Id
@Entity @Table(name="Test01") public class Test01 implements Serializable{ private static final long serialVersionUID = 3524215936351012384L; private String address ; private int age ; private String email ; private String phone ; @Id private TestKey01 testKey ;}
主鍵類:
@Embeddable public class Testkey01 implements Serializable{ private static final long serialVersionUID = -3304319243957837925L; private long id ; private String name ; /** * @return the id */ public long getId() { return id; } /** * @param id the id to set */ public void setId(long id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } @Override public boolean equals(Object o) { if(o instanceof Testkey0101){ Testkey01 key = (TestKey01)o ; if(this.id == key.getId() && this.name.equals(key.getName())){ return true ; } } return false ; } @Override public int hashCode() { return this.name.hashCode(); } }
二、將聯合主鍵的欄位單獨放在一個類中,該類需要實現java.io.Serializable介面並重寫equals和hascode,最後在主類中(該類不包含聯合主鍵類中的欄位)儲存該聯合主鍵類的一個引用,並產生set和get方法,並將該引用註解為@EmbeddedId
@Entity @Table(name="Test02") public class Test02 { private String address ; private int age ; private String email ; private String phone ; @EmbeddedId private TestKey02 testKey ;}
Testkey02為普通Java類即可。
三、將聯合主鍵的欄位單獨放在一個類中,該類需要實現java.io.Serializable介面並要重寫equals和hashcode.最後在主類中(該類包含聯合主鍵類中的欄位)將聯合主鍵欄位都註解為@Id,並在該類上方將上這樣的註解:@IdClass(聯合主鍵類.class)
@Entity @Table(name="Test03") @IdClass(TestKey03.class) public class Test03 { @Id private long id ; @Id private String name ; }
Testkey03為普通Java類即可。
Hibernate註解映射聯合主鍵的三種主要方式