7

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?

amit bhardwaj
  • 883
  • 2
  • 8
  • 18
ikazxc56
  • 105
  • 2
  • 6
  • You're just setting flags. deleted=1, deleted=0. It's not actually deleting. I don't understand what are you trying to accomplish by doing this. – sergiu Mar 25 '15 at 08:59

1 Answers1

2

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 ")
JTai
  • 36
  • 4
  • This can hardly be the best way as it is polluting the entities with a lot of data access logic. Doing it by overriding base repository methods would be a better way if possible. If it is not possible, then this is pretty much the only way. Definitely not a nice way. – aycanadal Dec 04 '17 at 15:45