如果多个实体类都有 isDelete 字段,并且你希望在插入时为它们统一设置默认值,可以采取以下几种方法来减少代码重复:

1. 使用基类(抽象类)

创建一个基类,其中包含 isDelete 字段和 @PrePersist 方法。然后让所有需要这个字段的实体类继承这个基类。

示例代码:

import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist; @MappedSuperclass
public abstract class BaseEntity { protected Integer isDelete; @PrePersist
public void prePersist() {
if (isDelete == null) {
isDelete = 0; // 设置默认值为0
}
} // Getter 和 Setter
public Integer getIsDelete() {
return isDelete;
} public void setIsDelete(Integer isDelete) {
this.isDelete = isDelete;
}
}

然后在其他实体类中继承 BaseEntity

import javax.persistence.Entity;
import javax.persistence.Id; @Entity
public class MyEntity extends BaseEntity { @Id
private Long id; // 其他字段、getter 和 setter
}

2. 使用 AOP(面向切面编程)

通过 Spring AOP 创建一个切面,在插入操作时检查并设置 isDelete 的默认值。这种方式不需要修改每个实体类,适合大规模应用。

示例代码:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component; import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.lang.reflect.Field; @Aspect
@Component
public class DefaultValueAspect { @PersistenceContext
private EntityManager entityManager; @Before("execution(* com.example.repository.*.save(..))") // 根据你的仓库路径调整
public void setDefaultValues(Object entity) throws IllegalAccessException {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
if ("isDelete".equals(field.getName())) { // 检查字段名
field.setAccessible(true);
if (field.get(entity) == null) {
field.set(entity, 0); // 设置默认值为0
}
}
}
}
}

3. 使用 JPA 审计功能

使用 Spring Data JPA 的审计功能,通过实现 AuditorAware 接口来统一处理审计字段,包括 isDelete。这种方法适合需要更多审计信息的情况,但实现起来相对复杂。

总结

  • 基类:通过创建一个基类,所有需要 isDelete 字段的实体类都可以继承这个基类,避免重复代码。
  • AOP:使用 AOP 可以在插入时动态处理 isDelete 字段,适合大型项目。
  • JPA 审计功能:适合更复杂的审计需求,但实现较复杂。

选择合适的方法取决于你的项目需求和架构。

使用事件监听@EntityListeners

JPA 提供了事件监听器的功能,你可以定义一个事件监听器来处理所有需要设置默认值的实体类。

示例代码:

import javax.persistence.PostLoad;
import javax.persistence.PrePersist;
import javax.persistence.EntityListeners; public interface DeletedField { Integer getDeletedFlag(); void setDeletedFlag(Integer deletedFlag);
} public class DeleteDefaultValueListener { @PrePersist
public void setDefaultValues(DeletedFlagField deletedFlagField) {
if (deletedFlagField.getDeletedFlag() == null) {
deletedFlagField.setDeletedFlag(0); // 设置默认值为0
}
} } @EntityListeners(DefaultValueListener.class)
@Entity
public class TableUserAccount extends EntityBase implements DeletedFlagField { /**
* 删除标识(逻辑删除),1删除 0未删除
*/
@Column(name = "deleted_flag")
private Integer deletedFlag;
}

4. 扩展JPA,对建立者和更新者的扩展

  • CreatedByField
  • UpdatedByField
  • CreatedByDefaultValueListener
  • UpdatedByDefaultValueListener

CreatedByField

public interface CreatedByField {

	String getCreatedBy();

	void setCreatedBy(String createdBy);

}

扩展EntityBase实体,不使用默认的CreatedByLastModifiedBy

@Getter
@Setter
@MappedSuperclass
@EntityListeners({ AuditingEntityListener.class, UpdatedByDefaultValueListener.class,
CreatedByDefaultValueListener.class })
public abstract class EntityBase implements Serializable, CreatedByField, UpdatedByField { /**
* 创建人
*/
@Column(name = "created_by")
private String createdBy; /**
* 修改人
*/
@Column(name = "updated_by")
private String updatedBy;
}

CreatedByDefaultValueListener

public class CreatedByDefaultValueListener implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@PrePersist
public void setDefaultValues(CreatedByField createdByField) {
if (createdByField.getCreatedBy() == null) {
if (this.applicationContext.getBean(AuditorAwareImpl.class) != null) {
createdByField.setCreatedBy(
this.applicationContext.getBean(AuditorAwareImpl.class).getCurrentAuditor().orElse("")); }
}
} /**
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
} }

springboot~jpa优雅的处理isDelete的默认值的更多相关文章

  1. Spring boot Jpa添加对象字段使用数据库默认值

    Spring boot Jpa添加对象字段使用数据库默认值 jpa做持久层框架,项目中数据库字段有默认值和非空约束,这样在保存对象是必须保存一个完整的对象,但在开发中我们往往只是先保存部分特殊的字段其 ...

  2. 补习系列(19)-springboot JPA + PostGreSQL

    目录 SpringBoot 整合 PostGreSQL 一.PostGreSQL简介 二.关于 SpringDataJPA 三.整合 PostGreSQL A. 依赖包 B. 配置文件 C. 模型定义 ...

  3. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础授权权限

    上一篇<[原]无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限>介绍了实现Shiro的基础认证.本篇谈谈实现 ...

  4. 【原】无脑操作:IDEA + maven + Shiro + SpringBoot + JPA + Thymeleaf实现基础认证权限

    开发环境搭建参见<[原]无脑操作:IDEA + maven + SpringBoot + JPA + Thymeleaf实现CRUD及分页> 需求: ① 除了登录页面,在地址栏直接访问其他 ...

  5. 带着新人学springboot的应用08(springboot+jpa的整合)

    这一节的内容比较简单,是springboot和jpa的简单整合,jpa默认使用hibernate,所以本质就是springboot和hibernate的整合. 说实话,听别人都说spring data ...

  6. springboot+jpa+mysql+redis+swagger整合步骤

    springboot+jpa+MySQL+swagger框架搭建好之上再整合redis: 在电脑上先安装redis: 一.在pom.xml中引入redis 二.在application.yml里配置r ...

  7. SpringBoot JPA + H2增删改查示例

    下面的例子是基于SpringBoot JPA以及H2数据库来实现的,下面就开始搭建项目吧. 首先看下项目的整体结构: 具体操作步骤: 打开IDEA,创建一个新的Spring Initializr项目, ...

  8. SpringBoot JPA懒加载异常 - com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy

    问题与分析 某日忽然发现在用postman测试数据时报错如下: com.fasterxml.jackson.databind.JsonMappingException: could not initi ...

  9. SpringBoot如何优雅的使用RocketMQ

    目录 SpringBoot如何优雅的使用RocketMQ SpringBoot如何优雅的使用RocketMQ MQ,是一种跨进程的通信机制,用于上下游传递消息.在传统的互联网架构中通常使用MQ来对上下 ...

  10. IDEA SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统

    先放上github地址:spike-system,可以直接下载完整项目运行测试 SpringBoot+JPA+MySql+Redis+RabbitMQ 秒杀系统 技术栈:SpringBoot, MyS ...

随机推荐

  1. 配置 Windows Boot Manager

    配置 Windows Boot Manager 通常需要使用 bcdedit 命令,这是一个命令行工具,用于管理 Boot Configuration Data (BCD) 存储.BCD 存储包含了启 ...

  2. 【YashanDB知识库】EXP导致主机卡死问题

    问题现象 问题单:exp导出全库1主2备主节点执行,DMP文件30G左右系统卡死,发生主备切换 现象: exp sys/Cod-2022 file=bim20240402.dmp full=y 服务器 ...

  3. 使用 Dependify 工具探索 .NET 应用程序依赖项

    在大型项目中,由于各种组件的复杂性和互连性,管理依赖项可能变得具有挑战性.如果没有适当的工具或文档,可能很难浏览项目并对依赖项做出假设.以下是在大型项目中难以导航项目依赖项的几个原因: 复杂性:大型项 ...

  4. 小tips:HTML5的ruby标签实现给汉字加拼音、details标签实现折叠面板、原生进度条progress和度量meter

    ruby标签实现给汉字加拼音 ruby 元素由一个或多个字符(需要一个解释/发音)和一个提供该信息的 rt 元素组成,还包括可选的 rp 元素,定义当浏览器不支持 "ruby" 元 ...

  5. MyBatis——简介

    MyBatis MyBatis 是一款优秀的持久层框架,用于简化 JDBC 开发 官网:https://mybatis.net.cn/ 持久层 负责将数据保存到数据库的那一层代码 javaEE 三层架 ...

  6. SpringMVC —— 日期类型参数传递

    日期类型参数传递    相关注解    类型转换器   

  7. 离线安装MySQL

    离线安装mysql [下载地址](MySQL :: Download MySQL Community Server) 解压后依次执行如下命令 rpm -ivh mysql-community-comm ...

  8. 《MySQL 5.7从入门到精通(视频教学版)》代码课件教学视频下载

    <MySQL 5.7从入门到精通(视频教学版)>代码课件教学视频下载 https://pan.baidu.com/s/1ZufDV6a_PEnjp-Bdh4IkuQ 提取码:vgnr 无版 ...

  9. 16 模块time、datetime、random、hashlib、logging

    1. 时间模块time.datetime 在python中,表示时间有三种方式:时间戳 格式化的时间字符串(Format String): '2022-03-01' 时间元组(struct_time) ...

  10. Perfetto分析进阶

    一.Perfetto介绍 Perfetto是Android Q中引入的全新下一代平台级跟踪工具,为Android.Linux和Chrome平台提供了一种通用的性能检测和跟踪分析工具集.其核心是引入了一 ...