JPA @OneToMany and composite PK

若如初见. 提交于 2019-12-05 02:10:55

Good morning,

After a long day searching how JPA and @OneToMany works with composite PK, I did find a solution. In order to make it work, I used the parameter mappedBY of @OneToMany. As you can see in the code sample, I mapped the Set of Permission with the attribute action of the class Permission. And that's it! Simple when you know it!

FF

Action Class :

@Entity
@Table(name="action")
public class Action {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int num;

  @ManyToOne(cascade= { CascadeType.PERSIST, CascadeType.MERGE,
      CascadeType.REFRESH })
  @JoinColumn(name="domain_num")
  private Domain domain;

  private String name;
  private String description;

  @OneToMany(mappedBy="action")
  private Set<Permission> permissions;

Permission Class

@SuppressWarnings("serial")
@Entity
@Table(name="permission")
public class Permission implements Serializable {

  @EmbeddedId
  private PermissionPK primaryKey;

  @ManyToOne
  @JoinColumn(name="action_num", insertable=false, updatable=false)
  private Action action;

The error message seems pretty clear: you need to declare the three columns of your composite PK as @JoinColum and the name and referenceColumnName must be specified for each. I didn't test the mapping but try this:

@OneToMany
@JoinTable(name="permission", joinColumns= {
    @JoinColumn(name="col1", referencedColumnName="col1", nullable=false, updatable=false),
    @JoinColumn(name="col2", referencedColumnName="col2", ...),
    @JoinColumn(name="col3", referencedColumnName="col3", ...)
}, inverseJoinColumns= { @JoinColumn(name="num") })
private Set<Permission> permissions;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!