@OneToOne and @JoinColumn, automatically delete an empty entity, doable?

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; } 

The owner and the data have a one-to-one mapping, and the owner is the owner. The problem occurs when I execute: owner.setData (null); ownerDao.update (owner) ; The Owner Data_id table becomes null, that's right.

But the line "Data" is not deleted automatically. I have to write another DataDao and one more service level for transferring two actions (ownerDao.update (owner); dataDao.delete (data);)

Is it possible to make a data row automatically deleted if the owner has set the owner to zero?

+6
orm hibernate jpa one-to-one
source share
1 answer

Depending on the version of sleep mode, use:

use cascadeType annotation: DELETE_ORPHAN or orphanRemoval = true in @OneToOne annotation

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

I have never tried it on OneToOne, but from the document 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 post SO: Workarounds for the lack of Hibernate for orphan support for one-to-one and many-to-one relationships?

So it does not work. However, the two answers describe two different workarounds.

+8
source share

All Articles