Boris Pavlović
Boris Pavlović

Reputation: 64632

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

There's a table

master
  id int primary key

and

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

with JPA entities

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

and an identity class

class DetailId {
  Master master;
  String name;
}

In runtime Hibernate is complaining that it can not set an int to a Master field initializing the Detail class.

Any ideas?

Upvotes: 1

Views: 137

Answers (1)

v.ladynev
v.ladynev

Reputation: 19956

In the DetailId you can't use an entity: you need to change Master master to int master. And you need to implement Serializable

class DetailId implements Serializable {

  int master;

  String name;

}

Upvotes: 1

Related Questions