Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Soft Delete using update Cascade

In case I have 3 class which are connected each other.

Room Class

@Entity
@Table(name="table_room")
Class Room{
    @Id
    @GeneratedValue
    @Column(name="id_room")
    private Integer id;

    @Column(name="name")
    private String name;

    @OneToMany(mappedBy="room")
    private List<Person> people;

    @Column(name="deleted")
    private int deleted;
}

Person Class

 @Entity
@Table(name="table_person")
Class Person{
    @Id
    @GeneratedValue
    @Column(name="id_person")
    private Integer id;

    @Column(name="name")
    private String name;

    @ManyToOne
    @JoinColumn(name="id_room")
    private Room room;

    @OneToMany(mappedBy="person")
    private List<Phone> phones;

    @Column(name="deleted")
    private int deleted;
}

and then Phone Class

 @Entity
@Table(name="table_phone")
Class Phone{
    @Id
    @GeneratedValue
    @Column(name="id_person")
    private Integer id;

    @Column(name="name")
    private String name;

    @ManyToOne
    @JoinColumn(name="id_person")
    private Person person;

    @Column(name="deleted")
    private int deleted;
}

What i want to do here is implement soft delete with inserting value 1 to deleted column for deleted item and inserting value 0 for exist item. Also I want Cascading my deletion, so if any room deleted, then every person and phone which is related with that room will be also deleted("deleted" column value set to 1). My question is how can I do that on Hibernate? Is there any elegant way to implement this stuff?

like image 957
ikazxc56 Avatar asked Jun 02 '14 08:06

ikazxc56


1 Answers

The best way to achieve a soft delete with Hibernate is to use the @SQLDelete annotation on your classes.

make sure your mapping is set to cascade delete

calling session.delete(yourClass) should achive your soft delete

Hibernate doc

//used to overide the normal delete behavior
@SQLDelete(sql="UPDATE (table_name) SET deleted = '1' WHERE id = ?")
//optional Use this to exclude deleted element from get 
@Where(clause="deleted <> '1'")
//OR (Filter may also be used if you need to load deleted items occasionally)
@FilterDef(name="ProductFilter",defaultCondition="deleted <> 1 ")
like image 194
JTai Avatar answered Sep 18 '22 07:09

JTai