Reputation: 4606
So consider the following 2 tables:
table: User
id (pk)
...
and table UserProfile:
UserProfile
user_id(pk, and fk from User.id. fk is named profile_user_fk)
...
given this tables, I have the entity classes:
@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;
}
...
}
I don't want to add an extra column in UserProfile because I think this column is meaningless. User.id should be sufficient to indicate the identity of UserProfile records.
So I supposed the @OneToOne annotations will tell hibernate user is a pk and also fk and should refer to User.id for its own id; however executing the code shows:
org.hibernate.AnnotationException: No identifier specified for entity: xxx.UserProfile
Apparently what I thought was wrong - but I've no idea what can I do to fix it without altering the schema.
Any helps please. Thanks!
Upvotes: 0
Views: 1021
Reputation: 2807
The error
No identifier specified for entity: xxx.UserProfile
says
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.
Modify your UserProfile class as below :-
@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;
}
...
}
Read: @Entity & @Id and @GeneratedValue Annotations
Entity Class without Primary Key :
If you don't want to add primary key in UserProfile table then you can use @Embedded & @Embeddable annotations or <component>
tag in xml mapping. For more explanation on this look at below posts:-
<component>
or @Embedded & @Embeddable annotationsUpvotes: 1