Location>code7788 >text

springboot~jpa elegantly handles isDelete defaults

Popularity:737 ℃/2024-11-18 15:58:57

If multiple entity classes haveisDelete fields, and you want to set default values for them uniformly at insertion time, there are several approaches you can take to reduce code duplication:

1. Use of base classes (abstract classes)

Create a base class that containsisDelete fields and@PrePersist method. Then have all entity classes that require this field inherit from 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 to0
        }
    }

    // Getter cap (a poem) Setter
    public Integer getIsDelete() {
        return isDelete;
    }

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

and then inherited in other entity classesBaseEntity

import ;
import ;

@Entity
public class MyEntity extends BaseEntity {

    @Id
    private Long id;

    // Other fields、getter cap (a poem) setter
}

2. Use of AOP (cutter-oriented programming)

Create a cutout via Spring AOP that checks and sets theisDelete of the default values. This approach 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 to your warehouse path
    public void setDefaultValues(Object entity) throws IllegalAccessException {
        Field[] fields = ().getDeclaredFields();
        for (Field field : fields) {
            if ("isDelete".equals(())) { // Check field names
                (true);
                if ((entity) == null) {
                    (entity, 0); // Set the default value to0
                }
            }
        }
    }
}

3. Use of the JPA audit function

Use the auditing capabilities of Spring Data JPA by implementing theAuditorAware interface to unify the handling of audit fields, including createdBy,createdTime,updatedBy,updatedTime, etc., while theisDeleteThis status field is not implemented in the audit notes.

4. Using event listeners @EntityListeners

JPA provides event listener functionality. You can define an event listener to handle all the 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 to0
		}
	}

}

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

  	/**
	 * Delete logo(logical deletion),1removing 0未removing
	 */
	@Column(name = "deleted_flag")
	private Integer deletedFlag;
}

5. Extension of JPA to audit field builders and updaters

  • CreatedByField The Created By Field Interface
  • UpdatedByField Updated By Field Interface
  • CreatedByDefaultValueListener Builder Field Listener
  • UpdatedByDefaultValueListener Updated By Field Listener
  • AuditorAwareImpl Auditor interface, return current user

CreatedByField

public interface CreatedByField {

	String getCreatedBy();

	void setCreatedBy(String createdBy);

}

Extend EntityBase entities without using the defaultCreatedBycap (a poem)LastModifiedBy

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

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

	/**
	 * modifier
	 */
	@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;
	}

}