[英]Hibernate: map a foreign key that points to unique key
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?
如何使用Hibernate实现此映射? I make an @Embedable class for the composite primary key and in the entity I use it with annotation @EmbeddedId.
我为复合主键创建一个@Embedable类,并在实体中将其与注释@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. 这是第一个表中的唯一键,但是我遇到了一个例外: 引用com.users.maintenance.Code中的com.users.maintenance.User的外键具有错误的列数。 should be 2 .
应该是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;
}
}
}
You need tell Hibernate what User
columns you are referring to (if it's not a primary key). 您需要告诉Hibernate您要指的是“
User
列(如果它不是主键)。 To do this, add referencedColumnName
in the second entity: 为此,请在第二个实体中添加
referencedColumnName
:
@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: 我没有检查过,但是也许您还必须指定
User
类别中的code
列是唯一的:
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. 只需注意一点:不要公开所有字段,请正确使用封装。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.