Hibernate:映射指向唯一键的外键

时间:2013-12-09 08:36:44

标签: java hibernate persistence hibernate-mapping

我有一个包含两列复合主键的表,该表也有一个唯一键。另一个表中的唯一键被映射为外键。如何用Hibernate实现这个映射?我为复合主键创建一个@Embedable类,在实体中我使用注释@EmbeddedId。在第二个表中,我声明了一个字段:

 @ManyToOne
 @JoinColumn(name = "user_code", nullable = false)
 public User userCode;

这是第一个表中的唯一键,但我得到一个例外:从com.users.maintenance.Code引用com.users.maintenance.User的外键具有错误的列数。应该是2

修改 这是我的用户类:

 @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;
           }
      }
 }

1 个答案:

答案 0 :(得分:6)

您需要告诉Hibernate您所指的User列(如果它不是主键)。为此,请在第二个实体中添加referencedColumnName

 @ManyToOne
 @JoinColumn(name = "user_code", nullable = false, referencedColumnName = "code")
 public User userCode;

我没有检查过,但是您可能还需要指定code列在User类中是唯一的:

public class User {
...

      @Column(name = "code", unique=true)
      public int code;
...

正如旁注:不要公开所有字段,正确使用封装。