使用Hibernate获取多列主键

时间:2015-04-28 17:11:24

标签: java hibernate primary-key composite-primary-key

说我有一个看起来像这样的课程:

public class MyClass {
  @Id
  @Column(name = "ID")
  private long Id;
}

我可以使用hibernate会话对类进行get或load,如下所示:

MyClass a = (MyClass)session.get(MyClass.class, new Long(100));

但是,假设我有一个以多列为主键的类:

public MyJoinClass implements Serializable {
  private static final long serialVersionUID = -5L;
  @Id
  @Column(name = "ID")
  private long id;

  @Id
  @Column(name = "EMAIL_ADDRESS_ID")
  private long emailAddressId;
}

是否可以使用get或load这样的类?

2 个答案:

答案 0 :(得分:7)

尝试使用@IdClass@EmbeddedId

public MyJoinClass implements Serializable {
  private static final long serialVersionUID = -5L;

  @EmbeddedId
  private MyJoinClassKey key;
}

public MyJoinClassKey implements Serializable{

  @Column(name = "ID")
  private long id;

  @Column(name = "EMAIL_ADDRESS_ID")
  private long emailAddressId;
}

然后使用

MyJoinClass a = (MyJoinClass )session.get(MyJoinClass .class, new MyJoinClassKey (1, "email"));

看看这个问题,this被广泛解释。基本上,hibernate有复合键的机制。

答案 1 :(得分:0)

在休眠模式下是(documentation):

MyJoinClass a = session.get(MyJoinClass.class, new MyJoinClass(100, 200));

只需确保具有组合键所有部分的构造函数(并且不要忘记没有参数的默认公共构造函数):

public MyJoinClass implements Serializable {
  private static final long serialVersionUID = -5L;
  @Id
  @Column(name = "ID")
  private long id;

  @Id
  @Column(name = "EMAIL_ADDRESS_ID")
  private long emailAddressId;

  public MyJoinClass() {}

  public MyJoinClass(long id, long emailAddressId) {
    this.id= id;
    this.emailAddressId= emailAddressId;
  }
}