JPA从复合键中找到

时间:2013-10-08 20:03:24

标签: jpa

我有一个这样的课......

@Entity
public class User{
  private String userId;
  @Id
  public String getUserId(){
    return userId;
  }
  public void setUserId(String userId){
    this.userId = userId;
  }
}

@Embeddible
public class RegPk{
  private String serial;
  private String userId;
  ....
}

@Entity
@IdClass(RegPk.class)
public class Registration {
  private String userId, serial;

  private User user

  @Id
  @Column(name="SRL_C")
  public String getSerial() {return serial;}
  public void setSerial(String serial) {this.serial = serial;}
  @ManyToOne(cascade={CascadeType.REFRESH})
  @JoinColumn(name="USERID", referencedColumnName="USERID", nullable = false)
  public User getUser() {return user;}
  public void setUser(User user) {this.user = user;}
  @Id
  @Column(name="USERID", nullable = false)
  public String getUserId() {
    return userId;
  }
  public void setUserId(String userId) {
    this.userId = userId;
  }

}

RegPk pk = new RegPk();
pk.setSerial(dr.getSerial());
pk.setUserId(dr.getUserId());
Registration userOld =  em.find(Registration.class, pk);

但是当我尝试运行它时,我得到了null。我发誓,我以为我有这样的工作......

1。)这种事情甚至可能吗? 2.)我做错了什么?

1 个答案:

答案 0 :(得分:1)

是的,只要您使用MapsId annotation,就可以。否则,您有两个不同的字段映射到同一列,这是无效的。

javadoc提供的示例几乎与您的情况完全匹配。