Hibernate foreign key as part of primary key

老子叫甜甜 提交于 2019-11-29 02:06:16

There is an example which is completely similar to your case in the Hibernate reference documentation. Just before this example, you'll find the explanations. Here's the example, which matches your problem (User is table A, and Customer is table B):

@Entity
class Customer {
   @EmbeddedId CustomerId id;
   boolean preferredCustomer;

   @MapsId("userId")
   @JoinColumns({
      @JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
      @JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
   })
   @OneToOne User user;
}

@Embeddable
class CustomerId implements Serializable {
   UserId userId;
   String customerNumber;

   //implements equals and hashCode
}

@Entity 
class User {
   @EmbeddedId UserId id;
   Integer age;
}

@Embeddable
class UserId implements Serializable {
   String firstName;
   String lastName;

   //implements equals and hashCode
}

Note: it would be much much simpler of you had a surrogate identifier for those two tables. Unless you're forced to deal with a legacy schema, do yourself a favor and use surrogate keys.

Use @PrimaryKeyJoinColumn and @PrimaryKeyJoinColumns annotations. From Hibernate manual:

The @PrimaryKeyJoinColumn annotation does say that the primary key of the entity is used as the foreign key value to the associated entity.

public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 5478661842746845130L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
}
@Entity
public class Author {

    @Id
    @Column(name = "AUTHOR_ID", nullable = false)
    private int authorId;
    @Column(name = "ENABLED", nullable = false, length = 1)
    private boolean enabled;

    @OneToOne
    @MapsId
    @JoinColumn(name = "AUTHOR_ID", referencedColumnName = "ID", nullable = false, insertable = false, updatable = false)
    User user;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!