Hibernate version: 3.2.4.sp1
Hibernate annotation version: 3.3.0.ga
Hibernate entity manager version: 3.3.1.ga
Database: Oracle 10g
Hi,
I've been trying to do a one-to-one relationship using the same primary key. It seems that it's way more complex than expected. First, here's my final working result.
Deal is aggregating a DealState objet in a one-to-one relationship with a cascade
Code:
@Entity
@Table(name = "DEAL")
@SequenceGenerator(name = "DEAL_SEQ", sequenceName = "DEAL_SEQ")
public class Deal {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "DEAL_SEQ")
public long getId()
{
return id;
}
@OneToOne(optional = true, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
@ForeignKey(name = "FK_DEAL_STATE_DEAL")
public DealState getState()
{
return state;
}
public void setWorkflowState(DealState state)
{
this.state = state;
this.state.setDeal(this);
}
}
@Entity
@Table(name = "DEAL_STATE")
public class DealState {
@Id
@GeneratedValue(generator = "system-foreign")
@GenericGenerator(name = "system-foreign", strategy = "foreign", parameters = {
@Parameter(name = "property", value = "deal")
})
@Column(name = "ID_DEAL", nullable = false, insertable = true, updatable = false)
public long getId()
{
return id;
}
@OneToOne(optional = false, mappedBy = "state")
public Deal getDeal()
{
return deal;
}
public void setDeal(Deal deal)
{
this.deal = deal;
}
}
Then the comments:
1- I had to put a back pointer from DealState to Deal
2- This back pointer is used with the foreign generator strategy to set the id to the Deal state. This strategy doesn't seem documented.
3- On getState, @OneToOne was set optional even if it's not. The optional parameter is used to deduce the constrained parameter. If optional is not true, the entities aren't same in the right order. I don't understand why these not explicit constrained parameter to set (like in the hbm.xml mapping).
My obvious question is:
Am I doing it right? Isn't there any easier way to do the same thing? (which could explain why the documentation doesn't provide a complete explanation)
Thanks,
Henri