簡體   English   中英

在另一個充當主鍵的實體上休眠一對一映射

[英]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>標記。 有關此內容的更多說明,請參見以下帖子:-

  1. 使用<component>或@Embedded和@Embeddable批注
  2. 休眠且無PK
  3. 沒有@Id的休眠/持久性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM