简体   繁体   中英

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;

.....

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM