LoneWolf
LoneWolf

Reputation: 505

Mapping JPA entity with composite key

I am trying to map an entity with a composite key, but I need the composite key to be the id of other entity and a String, this is my class at the moment but I believe there may be something wrong.

@Entity
public class Permission implements Serializable {
    @Id
    @Column
    private String permission;

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "role_id", foreignKey = @ForeignKey(name = "fk_permission_role_id"))
    private Role role;

.....

Upvotes: 0

Views: 179

Answers (1)

Chris
Chris

Reputation: 21145

Assuming the ID in role is a simple Integer, you might use something like:

public class PermissionPK implements Serializable {
    private String permission;
    private Integer role;
}

And then add the @IdClass annotation to your entity:

@IdClass(PermissionPK.class)
@Entity
public class Permission implements Serializable {
  @Id
  private String permission;

  @Id
  @ManyToOne(optional = false)
  @JoinColumn(name = "role_id")
  private Role role;
}

This will allow you to uses EmployeePK instances in find operations, but it isn't needed for anything else.

Upvotes: 1

Related Questions