当前位置: 代码网 > it编程>编程语言>Java > SpringData JPA审计功能(@CreatedDate与@LastModifiedDate)实现

SpringData JPA审计功能(@CreatedDate与@LastModifiedDate)实现

2025年04月14日 Java 我要评论
引言在企业级应用开发中,数据审计是一项至关重要的功能。所谓数据审计,是指对数据的创建、修改等操作进行跟踪记录,以便于后续的数据分析、问题追踪和安全审核。spring data jpa提供了强大的审计功

引言

在企业级应用开发中,数据审计是一项至关重要的功能。所谓数据审计,是指对数据的创建、修改等操作进行跟踪记录,以便于后续的数据分析、问题追踪和安全审核。spring data jpa提供了强大的审计功能,通过简单的注解配置,即可实现对实体创建时间、最后修改时间、创建人和修改人的自动记录。本文将深入探讨spring data jpa的审计功能,重点介绍@createddate与@lastmodifieddate注解的实现原理及使用方法,帮助开发者构建健壮的数据审计系统。

一、spring data jpa审计功能概述

spring data jpa的审计功能是通过实体生命周期事件和aop切面实现的。它可以在实体被持久化和更新时,自动填充审计字段,从而避免了手动设置这些值的繁琐工作。

1.1 核心审计注解

spring data jpa提供了四个核心的审计注解:

  • @createddate:标记实体创建时间字段
  • @lastmodifieddate:标记实体最后修改时间字段
  • @createdby:标记实体创建者字段
  • @lastmodifiedby:标记实体最后修改者字段

这些注解都位于org.springframework.data.annotation包中,是spring data通用的审计注解,不仅限于jpa使用。

1.2 审计功能的工作原理

spring data jpa的审计功能主要通过以下几个组件协同工作:

  • auditingentitylistener:jpa实体监听器,负责捕获实体的生命周期事件
  • auditinghandler:处理审计信息的填充逻辑
  • datetimeprovider:提供当前时间的接口
  • auditoraware:提供当前用户信息的接口

当启用审计功能后,每当实体被创建或更新,auditingentitylistener会捕获相应的事件,并调用auditinghandler对标记了审计注解的字段进行填充。

二、基础配置

要使用spring data jpa的审计功能,首先需要进行必要的配置。

2.1 启用jpa审计功能

在spring boot应用中,通过@enablejpaauditing注解启用jpa审计功能:

package com.example.config;

import org.springframework.context.annotation.configuration;
import org.springframework.data.jpa.repository.config.enablejpaauditing;

/**
 * jpa审计功能配置类
 */
@configuration
@enablejpaauditing  // 启用jpa审计功能
public class jpaauditingconfig {
    // 可以在这里配置审计相关的bean
}

2.2 创建审计基类

通常,我们会创建一个包含审计字段的基类,让需要审计的实体继承这个基类:

package com.example.entity;

import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifieddate;
import org.springframework.data.jpa.domain.support.auditingentitylistener;

import javax.persistence.column;
import javax.persistence.entitylisteners;
import javax.persistence.mappedsuperclass;
import java.time.localdatetime;

/**
 * 包含审计字段的基础实体类
 */
@mappedsuperclass
@entitylisteners(auditingentitylistener.class)  // 注册实体监听器
public abstract class auditableentity {
    
    @createddate
    @column(name = "created_date", updatable = false)
    private localdatetime createddate;
    
    @lastmodifieddate
    @column(name = "last_modified_date")
    private localdatetime lastmodifieddate;
    
    // getter和setter方法
    public localdatetime getcreateddate() {
        return createddate;
    }
    
    public void setcreateddate(localdatetime createddate) {
        this.createddate = createddate;
    }
    
    public localdatetime getlastmodifieddate() {
        return lastmodifieddate;
    }
    
    public void setlastmodifieddate(localdatetime lastmodifieddate) {
        this.lastmodifieddate = lastmodifieddate;
    }
}

在上面的代码中:

  • @mappedsuperclass注解表明这是一个映射超类,其字段将被映射到子类的表中
  • @entitylisteners(auditingentitylistener.class)注册了jpa实体监听器,用于捕获实体的生命周期事件
  • @createddate标记了实体创建时间字段
  • @lastmodifieddate标记了实体最后修改时间字段
  • updatable = false确保createddate字段在更新时不会被修改

三、实现时间审计

时间审计是最基本的审计功能,涉及到@createddate@lastmodifieddate注解的使用。

3.1 使用审计基类

创建业务实体类并继承审计基类:

package com.example.entity;

import javax.persistence.*;
import java.math.bigdecimal;

/**
 * 产品实体类
 */
@entity
@table(name = "tb_product")
public class product extends auditableentity {
    
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    
    @column(name = "name", nullable = false)
    private string name;
    
    @column(name = "description")
    private string description;
    
    @column(name = "price", precision = 10, scale = 2)
    private bigdecimal price;
    
    @column(name = "stock")
    private integer stock;
    
    // getter和setter方法省略
}

继承auditableentity后,product实体将自动拥有createddatelastmodifieddate字段,这些字段会在实体创建和更新时自动填充。

3.2 不使用基类的审计实现

如果因为某些原因不想使用继承,也可以直接在实体类中使用审计注解:

package com.example.entity;

import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifieddate;
import org.springframework.data.jpa.domain.support.auditingentitylistener;

import javax.persistence.*;
import java.time.localdatetime;

/**
 * 订单实体类
 */
@entity
@table(name = "tb_order")
@entitylisteners(auditingentitylistener.class)  // 直接在实体类上注册监听器
public class order {
    
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    
    @column(name = "order_number", nullable = false, unique = true)
    private string ordernumber;
    
    @column(name = "customer_id")
    private long customerid;
    
    @column(name = "total_amount", precision = 10, scale = 2)
    private bigdecimal totalamount;
    
    @column(name = "status")
    private string status;
    
    @createddate
    @column(name = "created_date", updatable = false)
    private localdatetime createddate;
    
    @lastmodifieddate
    @column(name = "last_modified_date")
    private localdatetime lastmodifieddate;
    
    // getter和setter方法省略
}

3.3 自定义日期时间提供者

如果需要自定义日期时间的提供方式,可以实现datetimeprovider接口:

package com.example.audit;

import org.springframework.data.auditing.datetimeprovider;
import org.springframework.stereotype.component;

import java.time.localdatetime;
import java.time.zoneid;
import java.time.temporal.temporalaccessor;
import java.util.optional;

/**
 * 自定义日期时间提供者
 */
@component
public class customdatetimeprovider implements datetimeprovider {
    
    @override
    public optional<temporalaccessor> getnow() {
        // 使用特定时区的当前时间
        return optional.of(localdatetime.now(zoneid.of("asia/shanghai")));
    }
}

然后在配置类中注册这个提供者:

package com.example.config;

import com.example.audit.customdatetimeprovider;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.auditing.datetimeprovider;
import org.springframework.data.jpa.repository.config.enablejpaauditing;

/**
 * jpa审计功能配置类
 */
@configuration
@enablejpaauditing(datetimeproviderref = "datetimeprovider")  // 指定日期时间提供者
public class jpaauditingconfig {
    
    @bean
    public datetimeprovider datetimeprovider() {
        return new customdatetimeprovider();
    }
}

四、实现用户审计

除了时间审计,还可以实现用户审计,即记录创建和修改实体的用户。

4.1 扩展审计基类

扩展审计基类,添加用户审计字段:

package com.example.entity;

import org.springframework.data.annotation.createdby;
import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifiedby;
import org.springframework.data.annotation.lastmodifieddate;
import org.springframework.data.jpa.domain.support.auditingentitylistener;

import javax.persistence.column;
import javax.persistence.entitylisteners;
import javax.persistence.mappedsuperclass;
import java.time.localdatetime;

/**
 * 包含完整审计字段的基础实体类
 */
@mappedsuperclass
@entitylisteners(auditingentitylistener.class)
public abstract class fullauditableentity {
    
    @createddate
    @column(name = "created_date", updatable = false)
    private localdatetime createddate;
    
    @lastmodifieddate
    @column(name = "last_modified_date")
    private localdatetime lastmodifieddate;
    
    @createdby
    @column(name = "created_by", updatable = false)
    private string createdby;
    
    @lastmodifiedby
    @column(name = "last_modified_by")
    private string lastmodifiedby;
    
    // getter和setter方法省略
}

4.2 实现auditoraware接口

要使用@createdby@lastmodifiedby注解,需要实现auditoraware接口,提供当前用户信息:

package com.example.audit;

import org.springframework.data.domain.auditoraware;
import org.springframework.security.core.authentication;
import org.springframework.security.core.context.securitycontextholder;
import org.springframework.stereotype.component;

import java.util.optional;

/**
 * 当前用户提供者
 */
@component
public class springsecurityauditoraware implements auditoraware<string> {
    
    @override
    public optional<string> getcurrentauditor() {
        // 从spring security上下文中获取当前用户
        authentication authentication = securitycontextholder.getcontext().getauthentication();
        
        if (authentication == null || !authentication.isauthenticated()) {
            return optional.of("anonymoususer");
        }
        
        return optional.of(authentication.getname());
    }
}

然后在配置类中注册这个提供者:

package com.example.config;

import com.example.audit.customdatetimeprovider;
import com.example.audit.springsecurityauditoraware;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.data.auditing.datetimeprovider;
import org.springframework.data.domain.auditoraware;
import org.springframework.data.jpa.repository.config.enablejpaauditing;

/**
 * jpa审计功能配置类
 */
@configuration
@enablejpaauditing(
    datetimeproviderref = "datetimeprovider",
    auditorawareref = "auditoraware"  // 指定用户提供者
)
public class jpaauditingconfig {
    
    @bean
    public datetimeprovider datetimeprovider() {
        return new customdatetimeprovider();
    }
    
    @bean
    public auditoraware<string> auditoraware() {
        return new springsecurityauditoraware();
    }
}

4.3 使用完整审计实体

创建业务实体并继承完整审计基类:

package com.example.entity;

import javax.persistence.*;
import java.math.bigdecimal;

/**
 * 订单实体类
 */
@entity
@table(name = "tb_order")
public class order extends fullauditableentity {
    
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    
    @column(name = "order_number", nullable = false, unique = true)
    private string ordernumber;
    
    @column(name = "customer_id")
    private long customerid;
    
    @column(name = "total_amount", precision = 10, scale = 2)
    private bigdecimal totalamount;
    
    @column(name = "status")
    private string status;
    
    // getter和setter方法省略
}

五、实际应用场景

spring data jpa的审计功能在实际开发中有广泛的应用场景。

5.1 数据版本控制

结合版本控制字段,实现乐观锁和数据版本追踪:

package com.example.entity;

import javax.persistence.*;
import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifieddate;
import org.springframework.data.jpa.domain.support.auditingentitylistener;
import java.time.localdatetime;

/**
 * 文档实体类
 */
@entity
@table(name = "tb_document")
@entitylisteners(auditingentitylistener.class)
public class document {
    
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    
    @column(name = "title")
    private string title;
    
    @column(name = "content", columndefinition = "text")
    private string content;
    
    @version  // 版本控制字段
    @column(name = "version")
    private long version;
    
    @createddate
    @column(name = "created_date", updatable = false)
    private localdatetime createddate;
    
    @lastmodifieddate
    @column(name = "last_modified_date")
    private localdatetime lastmodifieddate;
    
    // getter和setter方法省略
}

5.2 审计日志记录

利用实体监听器,实现更详细的审计日志记录:

package com.example.listener;

import com.example.entity.auditlog;
import com.example.entity.product;
import com.example.repository.auditlogrepository;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;

import javax.persistence.postpersist;
import javax.persistence.postupdate;
import javax.persistence.prepersist;
import javax.persistence.preupdate;
import java.time.localdatetime;

/**
 * 产品审计监听器
 */
@component
public class productauditlistener {
    
    @autowired
    private auditlogrepository auditlogrepository;
    
    private static final threadlocal<product> originalstate = new threadlocal<>();
    
    @prepersist
    public void prepersist(product product) {
        // 新建产品前的操作
    }
    
    @postpersist
    public void postpersist(product product) {
        // 记录产品创建日志
        auditlog log = new auditlog();
        log.setentitytype("product");
        log.setentityid(product.getid().tostring());
        log.setaction("create");
        log.settimestamp(localdatetime.now());
        log.setdetails("created product: " + product.getname());
        
        auditlogrepository.save(log);
    }
    
    @preupdate
    public void preupdate(product product) {
        // 保存产品原始状态
        product original = new product();
        // 复制product的属性到original
        originalstate.set(original);
    }
    
    @postupdate
    public void postupdate(product product) {
        // 获取原始状态
        product original = originalstate.get();
        
        // 记录产品更新日志
        auditlog log = new auditlog();
        log.setentitytype("product");
        log.setentityid(product.getid().tostring());
        log.setaction("update");
        log.settimestamp(localdatetime.now());
        
        // 构建变更信息
        stringbuilder changes = new stringbuilder();
        if (!product.getname().equals(original.getname())) {
            changes.append("name changed from '")
                  .append(original.getname())
                  .append("' to '")
                  .append(product.getname())
                  .append("'. ");
        }
        // 其他字段变更检查...
        
        log.setdetails(changes.tostring());
        auditlogrepository.save(log);
        
        // 清理threadlocal
        originalstate.remove();
    }
}

要启用这个监听器,需要在product实体上注册:

@entity
@table(name = "tb_product")
@entitylisteners({auditingentitylistener.class, productauditlistener.class})
public class product extends auditableentity {
    // 实体内容
}

5.3 多租户审计

在多租户系统中,结合审计功能实现租户数据隔离:

package com.example.entity;

import org.springframework.data.annotation.createdby;
import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifiedby;
import org.springframework.data.annotation.lastmodifieddate;
import org.springframework.data.jpa.domain.support.auditingentitylistener;

import javax.persistence.column;
import javax.persistence.entitylisteners;
import javax.persistence.mappedsuperclass;
import java.time.localdatetime;

/**
 * 多租户审计基类
 */
@mappedsuperclass
@entitylisteners(auditingentitylistener.class)
public abstract class tenantauditableentity {
    
    @column(name = "tenant_id", nullable = false, updatable = false)
    private string tenantid;
    
    @createddate
    @column(name = "created_date", updatable = false)
    private localdatetime createddate;
    
    @lastmodifieddate
    @column(name = "last_modified_date")
    private localdatetime lastmodifieddate;
    
    @createdby
    @column(name = "created_by", updatable = false)
    private string createdby;
    
    @lastmodifiedby
    @column(name = "last_modified_by")
    private string lastmodifiedby;
    
    // getter和setter方法省略
}

使用多租户审计实体:

package com.example.entity;

import javax.persistence.*;

/**
 * 客户实体类
 */
@entity
@table(name = "tb_customer")
public class customer extends tenantauditableentity {
    
    @id
    @generatedvalue(strategy = generationtype.identity)
    private long id;
    
    @column(name = "name")
    private string name;
    
    @column(name = "email")
    private string email;
    
    @column(name = "phone")
    private string phone;
    
    // getter和setter方法省略
}

六、高级技巧

spring data jpa审计功能还有一些高级用法,可以满足更复杂的审计需求。

6.1 条件审计

有时候我们只希望在特定条件下进行审计。可以通过自定义实体监听器实现:

package com.example.listener;

import com.example.entity.user;
import org.springframework.data.annotation.createddate;
import org.springframework.data.annotation.lastmodifieddate;

import javax.persistence.prepersist;
import javax.persistence.preupdate;
import java.lang.reflect.field;
import java.time.localdatetime;

/**
 * 条件审计监听器
 */
public class conditionalauditlistener {
    
    @prepersist
    public void touchforcreate(object target) {
        // 只对激活状态的用户进行审计
        if (target instanceof user) {
            user user = (user) target;
            if (user.isactive()) {
                setcreateddate(user);
            }
        }
    }
    
    @preupdate
    public void touchforupdate(object target) {
        // 只对激活状态的用户进行审计
        if (target instanceof user) {
            user user = (user) target;
            if (user.isactive()) {
                setlastmodifieddate(user);
            }
        }
    }
    
    private void setcreateddate(object target) {
        setfieldvalue(target, createddate.class, localdatetime.now());
    }
    
    private void setlastmodifieddate(object target) {
        setfieldvalue(target, lastmodifieddate.class, localdatetime.now());
    }
    
    private void setfieldvalue(object target, class annotation, object value) {
        try {
            for (field field : target.getclass().getdeclaredfields()) {
                if (field.isannotationpresent(annotation)) {
                    field.setaccessible(true);
                    field.set(target, value);
                }
            }
        } catch (illegalaccessexception e) {
            throw new runtimeexception("failed to set auditing field", e);
        }
    }
}

6.2 自定义审计注解

可以创建自定义审计注解,实现更灵活的审计逻辑:

package com.example.annotation;

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

/**
 * 自定义审计注解:记录字段的历史值
 */
@retention(retentionpolicy.runtime)
@target(elementtype.field)
public @interface trackchanges {
    string value() default "";
}

然后实现对应的监听器处理这个注解:

package com.example.listener;

import com.example.annotation.trackchanges;
import com.example.entity.fieldchangelog;
import com.example.repository.fieldchangelogrepository;
import org.springframework.beans.factory.annotation.autowired;

import javax.persistence.preupdate;
import java.lang.reflect.field;
import java.time.localdatetime;
import java.util.objects;

/**
 * 字段变更跟踪监听器
 */
public class fieldchangetrackinglistener {
    
    @autowired
    private fieldchangelogrepository changelogrepository;
    
    @preupdate
    public void preupdate(object entity) {
        try {
            // 获取实体id
            long entityid = getentityid(entity);
            string entitytype = entity.getclass().getsimplename();
            
            // 查找标记了@trackchanges的字段
            for (field field : entity.getclass().getdeclaredfields()) {
                trackchanges annotation = field.getannotation(trackchanges.class);
                if (annotation != null) {
                    field.setaccessible(true);
                    
                    // 获取字段新值
                    object newvalue = field.get(entity);
                    
                    // 从数据库获取原始实体和字段旧值
                    object originalentity = loadoriginalentity(entityid, entity.getclass());
                    field.setaccessible(true);
                    object oldvalue = field.get(originalentity);
                    
                    // 如果值发生变化,记录日志
                    if (!objects.equals(oldvalue, newvalue)) {
                        fieldchangelog changelog = new fieldchangelog();
                        changelog.setentitytype(entitytype);
                        changelog.setentityid(entityid);
                        changelog.setfieldname(field.getname());
                        changelog.setoldvalue(oldvalue != null ? oldvalue.tostring() : null);
                        changelog.setnewvalue(newvalue != null ? newvalue.tostring() : null);
                        changelog.setchangedat(localdatetime.now());
                        
                        changelogrepository.save(changelog);
                    }
                }
            }
        } catch (exception e) {
            throw new runtimeexception("failed to track field changes", e);
        }
    }
    
    private long getentityid(object entity) throws exception {
        // 获取实体id的逻辑
        // ...
        return null;
    }
    
    private object loadoriginalentity(long entityid, class<?> entityclass) {
        // 从数据库加载原始实体的逻辑
        // ...
        return null;
    }
}

总结

spring data jpa的审计功能提供了一种强大而灵活的机制,用于自动跟踪实体的创建和修改信息。通过使用@createddate和@lastmodifieddate注解,开发者可以轻松地实现时间审计;结合@createdby和@lastmodifiedby注解以及auditoraware接口,还可以实现用户审计。这些功能大大简化了审计系统的开发工作,使开发者能够专注于业务逻辑的实现。

在实际应用中,审计功能可以与版本控制、详细日志记录和多租户系统等场景结合,满足不同的业务需求。通过自定义实体监听器和审计注解,还可以实现更加复杂和灵活的审计逻辑。总之,spring data jpa的审计功能是构建健壮企业级应用的重要组成部分,对于提高系统的可追溯性和安全性具有重要意义。

到此这篇关于springdata jpa审计功能(@createddate与@lastmodifieddate)实现的文章就介绍到这了,更多相关springdata jpa审计内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com