Hi.
I have a class User which holds another class UserHistory (for additional data) in OneToOne mapping. When I persist User, a new record for UserHistory is automatically created. The problem is that when I set a
new instance of UserHistory in User and persist User, the
old UserHistory record is not deleted, even though no one points at it anymore.
Here is some sample code (with simpler classes) of the problem:
MyUser class:
Code:
@Entity
@Table(name = "MY_USER_TABLE")
public class MyUser
{
@Id
@Column(name = "MY_USER_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id = null;
@OneToOne(cascade = CascadeType.ALL)
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private UserHistory userHistory = null;
// getters and setters...
}
UserHistory class:
Code:
@Entity
@Table(name = "USER_HISTORY_TABLE")
public class UserHistory
{
@Id
@Column(name = "USER_HISTORY_ID")
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id = null;
private String name = null;
// getters and setters...
}
The persisting code:
Code:
MyUser user = new MyUser();
UserHistory originalData = new UserHistory("Original Data");
user.setHeldData(originalData);
session =startNewSession();
session.saveOrUpdate(user);
closeSession(session);
UserHistory newerData = new UserHistory("Newer Data");
user.setHeldData(newerData);
session = startNewSession();
session.saveOrUpdate(user);
closeSession(session);
After the second "saveOrUpdate" the UserHistory table contains both records, even though the first one has just become orphan.
Is there an automatic way to get hibernate to delete such records (or maybe another way, not using OneToOne, to keep UserHistory in MyUser so that is deleted automatically - note that I cannot @Embedded since my real classes are far more complicated)?
Thanks,
Oz