请考虑以下两个表:
表:用户
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注释会告诉hibernate用户是pk还是fk,并且应该引用User.id来获取自己的id;但执行代码显示:
org.hibernate.AnnotationException: No identifier specified for entity: xxx.UserProfile
显然我认为错了 - 但我不知道如何在不改变架构的情况下修复它。
请帮忙。谢谢!
答案 0 :(得分:1)
错误
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 and @GeneratedValue Annotations
没有主键的实体类:
如果您不想在 UserProfile 表格中添加主键,则可以使用 @Embedded&amp; xml映射中的@Embeddable注释或 <component>
标记。有关此内容的更多解释,请参阅以下帖子: -