当前位置:网站首页>Soft deletion of data - when? How to realize it?

Soft deletion of data - when? How to realize it?

2022-06-10 19:52:00 InfoQ

0.  After reading this article, you will learn

  • What is soft deletion ?
  • How to consider whether to use soft deletion
  • How to be in Spring Soft deletion in

1.  Preface

In the process of developing the program , You will encounter a common requirement —— Delete data from table .

But sometimes , Business requirements require that the data in the database cannot be permanently deleted . For example, some sensitive information , We need to keep it for historical tracking .

This is the time , We will use soft deletion .

So what is soft deletion ? When can I use it ? In this paper , The author will take you to learn about soft deletion and how to use Spring Data JPA To achieve it .

2.  What is soft deletion (Soft Delete)?

2.1  The concept of soft deletion

Soft delete (Soft Delete) Is relative to hard deletion (Hard Delete) Speaking of , It can also be called logical deletion or mark deletion .

This deletion method does not really delete records from the database , Instead, this record is filtered out during query through a specific marking method . Although the data is no longer visible on the interface , But the database still exists .

2.2  Implementation of soft deletion

  • Add a Boolean field

Add something similar to
is_deleted
perhaps
is_active
perhaps
is_archived
Boolean field of , To mark whether to delete .

  • Add timestamp field

Add something similar to
deleted_at
The timestamp field of ,null Indicates not deleted , Not null It means that... Has been deleted , You can also get the deletion time .

  • Insert soft deleted data into another table .

for instance ,
order
The table will have a corresponding
order_deleted
surface , In the delete
order
Table data , Copy the data to
order_deleted
In the table .

In all three ways , The first 1 This is the most common way , It's also relatively simple ;

The first 2 Although for the second 1 This way will be more rigorous , Because it can get the exact deletion time . But the first 2 The two methods are relatively poor in query performance , because null Value will cause a full table scan , The query efficiency is greatly reduced .

We can mix the second 1 Species and 2 Ways of planting , Only the first 1 There are two ways to make conditions , Use the 2 Two ways of deleting time to supplement .

The first 3 Ways of planting , The idea is completely different from the first two ways , When there's a lot of data , We can consider adopting this strategy .

2.3  Whether to use soft deletion

In fact, in business logic “ Delete ” The word is inaccurate .

for instance , We “ Delete ” When you use a product, you actually mean us “ halt the sales ” 了 . Maybe we won't sell this product in the future , Customers will not see this product when searching , But the person in charge of the warehouse needs to manage its inventory for the time being .

therefore ,“ Delete ” It's an inaccurate statement , Just for convenience .

according to
Udi Dahan
According to the interpretation of :

  • The order is not deleted , But be “ Cancel ” Of , The order was cancelled too late , There will also be costs ;
  • Employees are not deleted , But be “ fire ” Or “ retired ” Of . There are also corresponding compensation to deal with ;
  • The position is not deleted , Be being “ fill ” Of ( Or the recruitment application is rejected ).

The real world is not cascading

Suppose the marketing department wants to delete an item from the catalogue , Does that mean that all old orders containing the product will disappear together ? Cascade... Go on , Should all invoices corresponding to these orders also be deleted ? Just delete it step by step , Is the company's profit and loss statement going to be redone ?

This seems obviously unreasonable .

Whether we use soft deletion in the actual business logic ?

The benefits of soft deletion are obvious , It's a medicine of regret , Facilitate historical tracking or for audit purposes (History tracking or audit).

Of course, soft deletion also has disadvantages , Not conducive to database performance ( Mainly for relational database ) The promotion of , A large amount of redundant data may be generated .

If we don't need , Please don't embellish the snake , When we need it , Please consider the data volume and reading and writing methods of the business .

When soft deletion is needed , Let's set a status field , Used to indicate whether the data is still valid . Of course , We can also use a field with multiple states : It works 、 Discontinue use 、 Cancel 、 Discard, etc . We can use such a status field to trace back past fields , To analyze it .

3.  stay Spring Soft deletion in

stay Spring Data JPA With the help of the , The implementation of soft deletion becomes very simple . We just need to add some comments .

Now let's see how to implement this function :

3.1  Entity class Product

detailed list 3.1.1  Entity class Product

package com.jayxu.mydemo.persistence.entity;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "product")
public class Product {

 private long id;

 private String name;

 private double price;

 private String description;

 private boolean isDeleted = Boolean.FALSE;

 // getter setter methods
}

In the above code , We added a Boolean property ——
isDeleted
Used to mark whether it has been deleted .

next step , We rewrite JPA Of delete command .

Generally speaking ,JPA Of delete Will run a command delete Of SQL, So let's first add some annotations to the above entity class :

detailed list 3.1.2  Added annotated entity class Product

@Entity
@Table(name = "product")
@SQLDelete(sql = "UPDATE product SET is_deleted = true WHERE id = ?")
@Where(clause = "is_deleted = false")
public class Product {
 // . . .
}

@SQLDelete
Comments are used to override delete command , Every time we execute delete On command , We'll turn it into a list 3.1.2 Medium UPDATE sentence , This command will
isDeleted
Change the field to true, Instead of permanently deleting data .

besides ,
@where
Comments will provide a filter , When we need to read
Product
Data time , The results will not include
is_deleted = true
The data of .

3.2 Repository

Repository Class has no special changes :

detailed list 3.2.1 ProductRepository

package com.jayxu.mydemo.repository;

import com.jayxu.mydemo.persistence.entity.Product;
import org.springframework.data.repository.CrudRepository;

public interface ProductRepository extends CrudRepository<Product, Long> {
}

3.3 Service

about Service Come on , There is nothing special .

In the following example , We created a record , Performed a soft delete , Find all entity classes .

detailed list 3.3.1 ProductService

package com.jayxu.mydemo.service;

import com.jayxu.mydemo.persistence.entity.Product;
import com.jayxu.mydemo.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

 @Autowired
 ProductRepository productRepository;

 public Product create(Product product){
 return productRepository.save(product);
 }

 public void deleteById(long id){
 productRepository.deleteById(id);
 }
 
 public Iterable<Product> findAll(){
 return productRepository.findAll();
 }
}

3.4  How to get deleted data

As mentioned above , For soft deleted data , We will use it for historical tracking or for other purposes . So how to get the data that has been soft deleted ?

Used
@Where
notes , We don't have the data , We can consider using
@FilterDef
and
@Filter
annotation . By using these annotations , We can dynamically add query criteria according to requirements .

detailed list 3.4.1  Entity class Product

package com.jayxu.mydemo.persistence.entity;

import org.hibernate.annotations.*;

import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = &quot;product&quot;)
@SQLDelete(sql = &quot;UPDATE product SET is_deleted = true WHERE id = ?&quot;)
@FilterDef(name = &quot;removedProductFilter&quot;
 , parameters = @ParamDef(name = &quot;isDeleted&quot;, type = &quot;boolean&quot;))
@Filter(name = &quot;removedProductFilter&quot;, condition = &quot;is_deleted = :isDeleted&quot;)
public class Product {
 // . . .
}

In the above code ,
@FilterDef 
Defined
@Filter
Parameters required for annotation .
@Filter
Generally used to define on entity classes .

In addition to this change , We need to rewrite
ProductService
Medium
findAll() 
Method .

detailed list 3.4.2  After modification ProductService

package com.jayxu.mydemo.service;

import com.jayxu.mydemo.persistence.entity.Product;
import com.jayxu.mydemo.repository.ProductRepository;
import org.hibernate.Filter;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;

@Service
public class ProductService {

 @Autowired
 ProductRepository productRepository;

 @Autowired
 EntityManager entityManager;

 private String FILTER_REMOVED_PRODUCT = &quot;removedProductFilter&quot;;

 private String PARAM_IS_DELETED = &quot;isDeleted&quot;;

 public Product create(Product product){
 return productRepository.save(product);
 }

 public void deleteById(long id){
 productRepository.deleteById(id);
 }

 public Iterable<Product> findAll(boolean isDeleted){
 Session session = entityManager.unwrap(Session.class);
 Filter removedProductFilter = session.enableFilter(FILTER_REMOVED_PRODUCT);
 removedProductFilter.setParameter(PARAM_IS_DELETED, isDeleted);

 Iterable<Product> products = productRepository.findAll();
 session.disableFilter(FILTER_REMOVED_PRODUCT);
 return products;
 }
}

In the list 3.4.2 in , Let's go through
session.enableFilter()
Activate defined
removedProductFilter
, Then set the passed in parameters , Then the query is completed , Finally through
session.disableFilter()
close
removedProductFilter
.

Of course, in addition to this way , We can also go directly to
ProductRepository
Write in
findAllByIsDeleted()
Method , This way is more concise , Try it on your own .

4.  Conclusion

I believe I can see here , Your concept of soft deletion 、 Consider whether soft deletion is needed and how to use Spring Data JPA Have a certain understanding of soft deletion , So now turn on the computer , Try this little function by yourself !

If you don't feel happy to see here , You can see my previous selections !


原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101743464337.html

随机推荐