简体   繁体   English

用组合键映射JPA实体

[英]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. 我正在尝试使用复合键映射一个实体,但是我需要将该复合键作为其他实体的ID和一个String,这是我目前的课程,但我相信可能出了问题。

@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: 假设角色中的ID是简单的Integer,则可以使用类似以下内容的代码:

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

And then add the @IdClass annotation to your entity: 然后将@IdClass批注添加到您的实体:

@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. 这将使您可以在查找操作中使用EmployeePK实例,但除此之外不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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