SoFunction
Updated on 2025-03-04

springboot jpa implements elegant processing of isDelete's default value

If multiple entity classes haveisDeleteFields, and you want to set default values ​​for them uniformly when inserting, you can take the following ways to reduce code duplication:

1. Use base class (abstract class)

Create a base class withisDeleteFields and@PrePersistmethod. Then let all entity classes that require this field inherit this base class.

Sample code:

import ;
import ;

@MappedSuperclass
public abstract class BaseEntity {

    protected Integer isDelete;

    @PrePersist
    public void prePersist() {
        if (isDelete == null) {
            isDelete = 0; // Set the default value to 0        }
    }

    // Getter and Setter    public Integer getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Integer isDelete) {
         = isDelete;
    }
}

Then inherit from other entity classesBaseEntity

import ;
import ;

@Entity
public class MyEntity extends BaseEntity {

    @Id
    private Long id;

    // Other fields, getters and setters}

2. Use AOP (Phase-oriented Programming)

Create a section through Spring AOP, check and set during insertion operationsisDeleteThe default value of  . This method does not require modification of each entity class and is suitable for large-scale applications.

Sample code:

import ;
import ;
import ;

import ;
import ;
import ;

@Aspect
@Component
public class DefaultValueAspect {

    @PersistenceContext
    private EntityManager entityManager;

    @Before("execution(* .*.save(..))") // Adjust according to your warehouse path    public void setDefaultValues(Object entity) throws IllegalAccessException {
        Field[] fields = ().getDeclaredFields();
        for (Field field : fields) {
            if ("isDelete".equals(())) { // Check the field name                (true);
                if ((entity) == null) {
                    (entity, 0); // Set the default value to 0                }
            }
        }
    }
}

3. Use JPA Audit Function

Using Spring Data JPA's audit function, implementAuditorAwareThe interface is used to handle audit fields uniformly, including createdBy, createdTime, updatedBy, updatedTime, etc.isDeleteThis status field is not implemented in audit comments.

4. Listen to @EntityListeners using event

JPA provides the function of event listeners, you can define an event listener to handle all entity classes that need to set default values.

Sample code:

import ;
import ;
import ;

public interface DeletedField {

  	Integer getDeletedFlag();

	void setDeletedFlag(Integer deletedFlag);
}

public class DeleteDefaultValueListener {

	@PrePersist
	public void setDefaultValues(DeletedFlagField deletedFlagField) {
		if (() == null) {
			(0); // Set the default value to 0		}
	}

}

@EntityListeners()
@Entity
public class TableUserAccount extends EntityBase implements DeletedFlagField {

  	/**
	  * Delete the identifier (logical deletion), 1 delete 0 not deleted
	  */
	@Column(name = "deleted_flag")
	private Integer deletedFlag;
}

5. Extend JPA, extensions to audit field builders and updaters

  • CreatedByField Creater Field Interface
  • UpdatedByField Updater Field Interface
  • CreatedByDefaultValueListener Created field listener
  • UpdatedByDefaultValueListener Updater field listener
  • AuditorAwareImpl audit interface, return to the current user

CreatedByField

public interface CreatedByField {

	String getCreatedBy();

	void setCreatedBy(String createdBy);

}

Extend the EntityBase entity without using the default CreatedBy and LastModifiedBy

@Getter
@Setter
@MappedSuperclass
@EntityListeners({ , ,
		 })
public abstract class EntityBase implements Serializable, CreatedByField, UpdatedByField {

	/**
	  * Created by
	  */
	@Column(name = "created_by")
	private String createdBy;

	/**
	  * Modified
	  */
	@Column(name = "updated_by")
	private String updatedBy;
	}

CreatedByDefaultValueListener

public class CreatedByDefaultValueListener implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@PrePersist
	public void setDefaultValues(CreatedByField createdByField) {
		if (() == null) {
			if (() != null) {
				(
						().getCurrentAuditor().orElse(""));

			}
		}
	}

	/**
	 * @param applicationContext
	 * @throws BeansException
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		 = applicationContext;
	}

}

This is the article about springboot jpa implementing elegant processing of isDelete default values. For more related content on springboot jpa processing of isDelete default values, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!