Reputation: 388
I have a table with composite primary key composed of two columns and that table also have a unique key. That unique key in another table is mapped as foreign key. How to implement this mapping with Hibernate? I make an @Embedable class for the composite primary key and in the entity I use it with annotation @EmbeddedId. In the second table I declare a field:
@ManyToOne
@JoinColumn(name = "user_code", nullable = false)
public User userCode;
which is the unique key from the first table, but I'm getting an exception: A Foreign key refering com.users.maintenance.User from com.users.maintenance.Code has the wrong number of column. should be 2.
Edit This is my User class:
@Entity
@Table(name = "Users")
public class User {
@EmbeddedId
public UserPk userId;
@column(name = "code")
public int code;
public UserPk getUserId() {
return this.userId;
}
public void setUserId(UserPk userId) {
this.userId = userId;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Embeddable
private class UserPk implements Seriazible {
@Column(name = "user_name")
public String userName;
@Column(name = "email")
public String email;
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
return this.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof UserPk)) {
return false;
}
UserPk pk = (UserPk)obj;
return pk.userName == userName && pk.email == email;
}
}
}
Upvotes: 2
Views: 4062
Reputation: 8906
You need tell Hibernate what User
columns you are referring to (if it's not a primary key). To do this, add referencedColumnName
in the second entity:
@ManyToOne
@JoinColumn(name = "user_code", nullable = false, referencedColumnName = "code")
public User userCode;
I haven't checked that, but maybe you will also have to specify that the code
column is unique in User
class:
public class User {
...
@Column(name = "code", unique=true)
public int code;
...
Just as a side note: don't make all fields public, use encapsulation properly.
Upvotes: 6