当键的一个元素是实体时,如何在 JPA 中声明复合键?

How to declare a composite key in JPA when one element of the key is an entity?

有个table

master
  id int primary key

detail
  master_id int references master(id),
  name string
  primary key (master_id, name)

使用 JPA 实体

@Entity
@Table(name = "master")
class Master {
  @Id
  private int id;
}

@Entity
@Table(name = "detail")
@IdClass(DetailId.class)
class Detail {
  @ManyToOne
  @JoinColumn(name = "master_id")
  @Id
  Master master;

  @Id
  String name;
}

和身份 class

class DetailId {
  Master master;
  String name;
}

在运行时 Hibernate 抱怨它无法将 int 设置为 Master 字段初始化 Detail class.

有什么想法吗?

DetailId 中您不能使用实体:您需要将 Master master 更改为 int master。你需要实施 Serializable

class DetailId implements Serializable {

  int master;

  String name;

}