[英]JPA / Hibernate unidirectional one-to-one mapping with shared primary key
[英]Hibernate one-to-one mapping on another entity acting as primary key
因此,請考慮以下2個表:
表:用戶
id (pk)
...
和表UserProfile:
UserProfile
user_id(pk, and fk from User.id. fk is named profile_user_fk)
...
給定此表,我有實體類:
@Entity
@Table(name="User")
public class User implements Serializable {
private int id;
private UserProfile profile;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false, unique = true)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@OneToOne(mappedBy = "user")
public UserProfile getProfie() {
return profile;
}
public void setProfile(UserProfile p) {
profile = p;
}
...
}
And the User class:
@Entity
@Table(name="UserProfile")
public class UserProfile implements Serializable {
private User user;
@OneToOne
@PrimaryKeyJoinColumn(name="profile_user_fk")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
...
}
我不想在UserProfile中添加額外的列,因為我認為此列毫無意義。 User.id應該足以表明UserProfile記錄的身份。
因此,我認為@OneToOne批注將告訴休眠用戶是pk還是fk,並應參考User.id作為其自身的ID; 但是執行代碼顯示:
org.hibernate.AnnotationException: No identifier specified for entity: xxx.UserProfile
顯然我認為是錯的-但我不知道在不更改架構的情況下可以如何解決。
任何幫助請。 謝謝!
錯誤
No identifier specified for entity: xxx.UserProfile
說
In your Entity class (UserProfile), you have not defined a primary key. You must specify
either @Id annotation or an @EmbeddedId annotation. Bcoz, every class defined as Entity
with @Entity annotation, needs an @Id or @EmbeddedId property.
如下修改您的UserProfile類:
@Entity
@Table(name="UserProfile")
public class UserProfile implements Serializable {
private long uProfileId;
private User user;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "uProfileId", nullable = false, unique = true)
public long getUProfileId() {
return uProfileId;
}
public void setUProfileId(long uProfileId) {
this.uProfileId = uProfileId;
}
@OneToOne
@PrimaryKeyJoinColumn(name="profile_user_fk")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
...
}
閱讀: @Entity&@Id和@GeneratedValue注釋
沒有主鍵的實體類:
如果您不想在UserProfile表中添加主鍵,則可以在XML映射中使用@Embedded&@Embeddable批注或<component>
標記。 有關此內容的更多說明,請參見以下帖子:-
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.