12

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 ?

smallufo
  • 11,516
  • 20
  • 73
  • 111

1 Answers1

19

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.

Community
  • 1
  • 1
Thierry
  • 5,270
  • 33
  • 39
  • 4
    Thank you , it works!!! And ... CascadeType.DELETE_ORPHAN is deprecated . It's replaced by @OneToOne(fetch=FetchType.EAGER , cascade=CascadeType.ALL , orphanRemoval=true) – smallufo Jun 17 '10 at 01:33
  • 2
    FetchType.EAGER is essential for orphan removal it seems. FetchType.LAZY orphan removal does not work. Hibernate version 4.3.10.FINAL. – Ben George Aug 24 '16 at 02:01
  • 1
    Using Hibernate 5.0.11.FINAL, this was sufficient for me `@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)`. I had success using either `FetchType.LAZY` or `FetchType.EAGER`. `EAGER` is default. – Dump Cake Dec 15 '16 at 16:02
  • Does this work if you call session.saveOrUpdate(Object), my current mapping isn't removing orphans with all those properties on the oneToOne annotation – Sean Malter Jul 12 '18 at 17:13