1
votes

I'm having a problem that I don't know if it's possible to solve just by using hibernate/jpa annotations. The problem is that I have a composite key that has the same column as one of my foreignkey composite id, and I would like to share this same column on the table. For example:

@Entity
class Id {
  @Id
  @Column(name = "idPessoa")
  public Integer idShared;
}

@Embeddable
class APK {
  @ManyToOne
  @JoinColumn(name = "idShared")
  public Id idShared;
  public String nKey;
}

@Entity
class A {
  @EmbeddedId
  public APK id;
}

@Embeddable
class BPK {
  @ManyToOne
  @JoinColumn(name = "idShared")
  public Id idShared;
  public Integer nCode;
}

@Entity
class B {
  @EmbeddedId
  public BPK id;

  @ManyToOne
  @JoinColumns({ @JoinColumn(name = "idShared", nullable = false, insertable = false, updatable = false), @JoinColumn(name = "nKey", nullable = false) })
  public A a;
}

The question is how I can share the column idShared between A and B and use it in the @ManyToOne for the foreign key?

I already tried to use @JoinColumn inside @JoinColumns with the name idShared but I get an error saying that I need to use insert = false and update = false, I already put insertable = false and updateable = false, but then I get another error saying that I can't mix things.

I found a possible solution saying to use:

@ManyToOne
@JoinColumnsOrFormulas(value = {
@JoinColumnOrFormula(formula = @JoinFormula(value = "idShared", referencedColumnName = "idShared")),
@JoinColumnOrFormula(column = @JoinColumn(name = "nKey", nullable = false)) })
public A a;

But it gives me the error:

Unable to find column with logical name  in table A

It appears that the "name" property of the column it has to find is blank someway.

Need some help please!

1
cant you make another class like idshared that have your shared id, and then join it to bpk and apk? - Angga
In fact in my current code idShared is a ForeignKey to another class, and both apk and bpk have this foreign key to idShared, but the problem is that I can't see how to share the same column when I want to make a FK to A inside B - loop0.brs
I think the solution is with JoinFormula thing, but I can't find documentation on how it works - loop0.brs

1 Answers

0
votes

Please have a look at Official Java EE 6 Tutorial about composite primary key. You can use @EmbeddedId @Embeddable and/or @IdClass annotations.

For example

// File: APK.java ---------------------
@Embeddable
public class APK implements Serializable {
  public Integer idShared;
  public String nKey;
}

// File: A.java ---------------------    
@Entity
public class A {
  @EmbeddedId public APK id;
}