I have an Entree object that contains a one-to-one relationship with a Ticket object, and this relationship is annotated with the @OneToOne(cascade = CascadeType.ALL) on the Entree side. I first insert this object into the db with hydration. The tables look like this--
Code:
ENTREE
entree_id | name | ticket_id
-----------------------
1 | DS 1 | 1
TICKET
ticket_id | number
---------------------
1 | 213
When I retrieve this object graph and disassociate with the session, I make changes to the graph like this-- entree.getTicket().setNumber(214).
Now I would expect that when I call session.merge(entree) that this would create/delete the changed record like this in the db--
Code:
ENTREE
entree_id | name | ticket_id
-----------------------
1 | DS 1 | 2
TICKET
ticket_id | number
---------------------
2 | 214
However, Hibernate does not delete the old record and thereby making it orphaned. This is what actually happened when I execute my code--
Code:
ENTREE
entree_id | name | ticket_id
-----------------------
1 | DS 1 | 2
TICKET
ticket_id | number
---------------------
1 | 213
2 | 214
Notice that the record with ticket_id = 1 is now orphaned. Since CascadeType.DELETE_ORPHAN is only used for one-to-many associations, how do I fix this so that there are no orphaned records for one-to-one relationships after a merge()? Below is my code
Code:
public class Entree {
private Long id;
private Ticket ticket;
private String name;
@Id
public Long getId() {
return this.id;
}
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="ticket_id")
public Ticket getTicket() {
return this.ticket;
}
// appropriate setters
}
public class Ticket {
private Long id;
private String number;
@Id
public Long getId() {
return this.id;
}
...
}
-Larry