May be this is a stupid question but in a database a column can be either a primary and a foreign-key, so why cannot a field/property be annotated to be both Id and ManyToOne ?
I have 3 classes :
Code:
@Entity
@Table(name="ORDINI")
@SequenceGenerator(sequenceName="HIBERNATE_SEQUENCE", name="SEQ")
public class Ordine {
@Id
@GeneratedValue(generator="SEQ")
private int id;
private int shipped;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
... getter/setter
}
@Entity
@Table(name="PRODOTTI")
@SequenceGenerator(sequenceName="HIBERNATE_SEQUENCE", name="SEQ")
public class Prodotto {
@Id
@GeneratedValue(generator="SEQ")
private int id;
... getter/setter
}
@Entity
@Table(name="RIGHE_ORDINE")
@IdClass(RigaOrdine.RighaOrdinePk.class)
public class RigaOrdine {
@Id
@Column(insertable=false, updatable = false)
[b]private Ordine ordine;[/b]
@Id
@Column(insertable=false, updatable = false)
[b]private Prodotto prodotto;[/b]
private int qty;
@Embeddable
public static class RighaOrdinePk implements Serializable {
@ManyToOne
@JoinColumn(name="ORD_ID")
[b]private Ordine ordine;[/b]
@ManyToOne
@JoinColumn(name="PROD_ID")
[b]private Prodotto prodotto;[/b]
... getter/setter/equals...
}
This works fine but there is a big problem : in the Ordine class i cannot define a @OneToMany property related to the ordine field in the RigaOrdine class.
This is because this field is already annotated as @Id and cannot be annotated also as @ManyToOne twice.
I've also tried to use the the ordine field in the inner PK class (already annotated as @ManyToOne) but i've not found a way to do that.
I've also tried to see what does the JPA tool in Eclipse generates starting from my database. The generated PK class looks like this one :
Code:
public class RigaOrdinePK implements Serializable {
@Column(name = "ord_id", nullable = false)
private int orderId;
@Column(name = "prod_id", nullable = false)
private int productId;
...
and the RigaOrdine :
Code:
@EmbeddedId
protected RigaOrdinePK rigaOrdinePK;
@Column(name = "qty", nullable = false)
private int qty;
@JoinColumn(name = "ord_id", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne
private Ordine ordine;
@JoinColumn(name = "prod_id", referencedColumnName = "id", insertable = false, updatable = false)
@ManyToOne
private Prodotto prodotto;
This works fine and in the Ordine class i can define may OneToMany relation. But i found this mapping not clear (in my model the Pk is the class, not the id value ..)
Do you have any suggestion on how to map this kind of composite key ?
TIA
Sergio Sette