views:

46

answers:

1

I have two Entities , with the following JPA annotations :

@Entity
@Table(name = "Owner")
public class Owner implements Serializable
{
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "id")
  private long id;

  @OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL)
  @JoinColumn(name="Data_id")
  private Data Data;  
}

@Entity
@Table(name = "Data")
public class Data implements Serializable
{
  @Id
  private long id;
}

Owner and Data has one-to-one mapping , the owning side is Owner. The problem occurs when I execute : owner.setData(null) ; ownerDao.update(owner) ; The "Owner" table's Data_id becomes null , that's correct.

But the "Data" row is not deleted automatically. I have to write another DataDao , and another service layer to wrap the two actions ( ownerDao.update(owner) ; dataDao.delete(data); )

Is it possible to make a data row automatically deleted when the owning Owner set it to null ?

+1  A: 

use the cascadeType : DELETE_ORPHAN

documentation : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/objectstate.html#objectstate-transitive

I've never tried it on OneToOne, but from the doc, it should work.

@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL)
@JoinColumn(name="Data_id")
@org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.DELETE_ORPHAN})
private Data Data;

EDIT: i found this SO post : http://stackoverflow.com/questions/913073/workarounds-for-hibernates-lack-of-delete-orphan-support-for-one-to-one-and-many

So perhap's it's not working. The two answers describe two different workarounds however.

Thierry
Thank you , it works!!!And ... CascadeType.DELETE_ORPHAN is deprecated . It's replaced by@OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL , orphanRemoval=true)
smallufo