@OneToOne and @JoinColumn, auto delete null entity , doable?

smallufo picture smallufo · Jun 14, 2010 · Viewed 22.6k times · Source

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 ?

Answer

Thierry picture Thierry · Jun 14, 2010

Depending on your hibernate version, use :

use the cascadeType : DELETE_ORPHAN or orphanRemoval=true on the @OneToOne annotation

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;

or

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

EDIT: i found this SO post : Workarounds for Hibernate's lack of delete-orphan support for one-to-one and many-to-one relationships?

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