Reputation: 5615
I have a transaction table which contains information about... transactions, some transactions are derived from a previous transaction, so that there can be a one to one relation between transactions.
I'm trying to set up annotation in hibernate to create this data structure, but I wasn't able to figure out or find how to do it.
@Entity
@Table(name="transaction")
public class Transaction {
private String transactionid;
private Transaction derivedFrom;
/**
* @return the transactionid
*/
@Id
public String getTransactionid() {
return transactionid;
}
/**
* @param transactionid the transactionid to set
*/
public void setTransactionid(String transactionid) {
this.transactionid = transactionid;
}
@OneToOne(mappedBy = "transaction", cascade = CascadeType.ALL)
public Transaction getDerivedFrom() {
return derivedFrom;
}
public void setDerivedFrom(Transaction derivedFrom) {
this.derivedFrom = derivedFrom;
}
}
Here is an example of code so you'll understand where I'm going with this... any idea on how to set up this relation?
Upvotes: 3
Views: 4123
Reputation: 42084
It does not work, because of
mappedBy="transaction"
calls for bidirectional relationship and attribute name transaction on the other side of relationship. As you see from your code, you do not have such an attribute.
If you want unidirectional one-to-one from child to parent, following is way to go:
public class Transaction {
private String transactionid;
private Transaction parent;
@Id
public String getTransactionid() {
return transactionid;
}
public void setTransactionid(String transactionid) {
this.transactionid = transactionid;
}
@OneToOne
public Transaction getParent() {
return parent;
}
public void setParent(Transaction parent) {
this.parent = parent;
}
}
Relationship is persisted by default to column name parent_transactionid
, this can of course be changed by @JoinColum. Additionally you likely want to set unique contraint to column.
To make relationship described above bidirectional one-to-one, just add following (no other modifications needed):
private Transaction child;
@OneToOne(mappedBy = "parent")
public Transaction getChild() {
return parent;
}
public void setChild(Transaction child) {
this.child = child;
}
Upvotes: 4
Reputation: 4333
Assuming you have a foreign key column "derived_id" in your transaction table, you can specify the join column
@Entity
public class Transaction
{
@OneToOne
@JoinColumn(name = "derived_id", nullable = true)
private Transaction derivedFrom;
}
Upvotes: 1