Wednesday, August 6, 2014

Soft Delete with JPA and EclipseLink

Assuming I have the following table.

And my entity
@Entity
@Table(name="ITEM")
public class Item {
    private Long itemId;
    private String itemName;
    private Integer itemStatus;

    // getter and setter
}

for AUDITING purpose, hard delete is not encouraged.
thus, when deleting a record, the ITEM_STAUS changes to 2 (deleted).

and I have the following status code
0 - active
1 - inactive
2 - deleted

To achieve this, we need a custom DescriptorCustomizer for the particular entity.
The DescriptorCustomizer will execute update sql on deletion instead of delete sql
public class SoftDeleteCustomizer implements DescriptorCustomizer {
public void customize(ClassDescriptor descriptor) {
  descriptor.getQueryManager()
    .setDeleteSQLString("Update ITEM set ITEM_STATUS = 2 where ITEM_ID = #ITEM_ID"); 
  } 
}

and add the SoftDeleteCustomizer to the Item entity.
@Entity
@Table(name="ITEM")
@Customizer(SoftDeleteCustomizer.class)
public class Item {
    ////

}

Finally, add @AdditionalCriteria to entity
@Entity
@Table(name="ITEM")
@Customizer(SoftDeleteCustomizer.class)
@AdditionalCriteria("this.itemStatus <> 2")
public class Item {
    ////

}

the @AdditionalCriteria annotation will always filter out the items with itemStatus = 2.
meaning all soft-deleted items are ignored, thus users only can see active records from the UI.
whereas, the soft-deleted records are still exist in DB for auditing purpose.


Done!!

1 comment:

  1. JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application. It is currently used as the replacement for complex entity beans. The implementation of JPA specification are provided by many vendors such as: Hibernate. best courses to learn spring data jpa

    ReplyDelete

LinkWithin

Related Posts Plugin for WordPress, Blogger...