在spring jpa audit 中,在字段或者方法上使用注解@CreatedDate@CreatedBy@LastModifiedDate@LastModifiedBy,当进行实体插入或者更新可以自动赋值

  • @CreatedDate 创建时间

  • @CreatedBy 创建人

  • @LastModifiedDate 更新时间

  • @LastModifiedBy 更新人

使用:

1.定义实体类,并使用注解标注字段

import lombok.Data;
import org.springframework.data.annotation.*;
import org.springframework.data.mongodb.core.mapping.Field; import java.time.LocalDateTime; @Data
public class BaseEntity {
@Id private String id;
@Field @CreatedBy private String createUserId; @Field @LastModifiedBy private String updateUserId; @Field @CreatedDate private LocalDateTime createTime; // 创建时间 @Field @LastModifiedDate private LocalDateTime updateTime; // 修改时间
}

2.添加 AuditorAware配置,设置默认用户

@Configuration
@EnableMongoAuditing(auditorAwareRef = "jpaAuditorAware")//使用mongo,也可以使用其他,如jpa(mysql)
public class JpaAuditorAware implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
return "system";
}
}

这里是直接设置了一个默认值,正常来说,应该使用springsecurity或者shiro,从请求token中获取当前登录用户,如:

public final class SecurityUtils {

  private SecurityUtils() {}

  /**
* 根据 Authorization 获取当前登录的用户
*
* @return 返回用户id
*/
public static String getCurrentUserId() {
SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
String userId = null;
if (authentication != null) {
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
userId = springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
userId = (String) authentication.getPrincipal();
}
}
return userId;
}
} //设置Auditor
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> { @Override
public String getCurrentAuditor() {
String userId= SecurityUtils.getCurrentUserId();
return userId;
}
}

3.新建 User类,继承BaseEntity

@Data
@Document(collection = "stu")
public class Stu extends BaseEntity
{ String name; String clazz; }

4.UserRepository 继承MongoRepository,连接mongo数据库

测试:

@RequestMapping("/user")
public User saveUser(String name) {
User user = new User();
user.setName(name);
return userRepo.save(user);
}

发现4个字段都自动赋值了。

但是有个问题,有些场景是这样的:

    User user = new User();
user.setName(name);
user.setCreateUserId("hahaha");//手动设置userId

等执行完数据库插入后,发现createUserId的值不是hahaha,还是上面默认的system

解决方法:实现Auditable接口,通过重载来自定义这些方法

@Data
public class Base extends BaseEntity implements Auditable<String, String> { @Override
public String getCreatedBy() {
return this.getCreateUserId();
} @Override
public void setCreatedBy(String s) {
//如果已经设置了createUserId,则取当前设置的;否则,使用当前登录的用户id(即参数s) 下同。
String createUserId = !StringUtils.isEmpty(getCreateUserId()) ? getCreateUserId() : s;
setCreateUserId(createUserId);
} @Override
public DateTime getCreatedDate() {
return new DateTime(
this.getCreateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
} @Override
public void setCreatedDate(DateTime dateTime) {
setCreateTime(
Instant.ofEpochMilli(dateTime.getMillis())
.atZone(ZoneId.systemDefault())
.toLocalDateTime());
} @Override
public String getLastModifiedBy() {
return this.getUpdateUserId();
} @Override
public void setLastModifiedBy(String s) {
String createUserId = !StringUtils.isEmpty(getUpdateUserId()) ? getUpdateUserId() : s;
setUpdateUserId(createUserId);
} @Override
public DateTime getLastModifiedDate() {
return new DateTime(
this.getUpdateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
} @Override
public void setLastModifiedDate(DateTime dateTime) {
setUpdateTime(
Instant.ofEpochMilli(dateTime.getMillis())
.atZone(ZoneId.systemDefault())
.toLocalDateTime());
} @Override
public boolean isNew() {
return this.getId() == null;
}
}

测试:新建实体类stu,继承Base

@Data
@Document(collection = "stu")
public class Stu extends Base {
String name;
String clazz;
}

web rest类:

@RequestMapping("/stu")
public String saveStu(String name) throws JsonProcessingException {
Stu stu = new Stu();
stu.setName(name);
stu.setClazz(random.nextInt() + "");
stu.setCreateUserId(name);//自定义createUserId
stu = stuRepo.save(stu);
return om.writeValueAsString(stu);
}

jpa Auditor 自动赋值与自定义 @CreatedBy @LastModifiedBy @CreatedDate @LastModifiedDate的更多相关文章

  1. @CreatedDate@CreatedBy@LastModifiedBy@LastModifiedDate

    启动类上加上@EnableJpaAuditing 实体类,注意需要加上@EntityListeners(AuditingEntityListener.class)这个注解才能使@CreatedDate ...

  2. 【js】将table的每个td的内容自动赋值给其title属性

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  3. Spring data mongodb @CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy SpringSecurityAuditorAware,只记录用户名

    要在Spring data mongodb 中使用@CreatedBy@LastModifiedBy@CreatedBy@LastModifiedBy  这四个注解 必须实现 SpringSecuri ...

  4. springboot~ObjectMapper~dto到entity的自动赋值

    实体与Dto自动赋值 在开发的过程中,实体之间相互赋值是很正常的事,但是我们一般的方法都通过set和get方法来进行的,如果要赋值的字段少那还行,但是需要赋值的字段超过10个,那就是个灾难,你会看到整 ...

  5. JPA中自动使用@Table(name = "userTab")后自动将表名、列名添加了下划线的问题

    一.问题 JPA中自动使用@Table(name = "userTab")后自动将表名.列名添加了下划线的问题,如下图: 二.解决 在application.properties文 ...

  6. PowerDesigner显示Common注释列并自动赋值

    PowerDesigner中默认不显示Common注释列,可根据以下步骤显示并紫东填充Name列内容. 1.显示Common注释列 2.运行VB Script脚本自动赋值 使用Shift+Ctrl+X ...

  7. C#读取对象实例的值和对对象的属性自动赋值方法

    using System; using System.Data; using System.Reflection; namespace DBUtility { /// <summary> ...

  8. 第三百四十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—cookie禁用、自动限速、自定义spider的settings,对抗反爬机制

    第三百四十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—cookie禁用.自动限速.自定义spider的settings,对抗反爬机制 cookie禁用 就是在Scrapy的配置文件set ...

  9. 反射学习2-通过反射机制动态获取属性的值模拟Struts的自动赋值

    一.准备知识:   Java反射机制   处理事务的JavaBean   String的操作常用方法 二.模拟步骤   这里我们通过反射机制动态获取属性的值模拟Struts中的自动赋值. 1.首先创建 ...

随机推荐

  1. DVWA-暴力破解学习笔记

    DVWA-暴力破解 1.暴力破解 2.burp安装证书 3.万能密码 一.暴力破解 burp四种暴力破解类型: sniper   一个字典,两个参数,先匹配第一项再匹配第二项 Battering ra ...

  2. zabbix监控交换机状态

    1.在Zabbix中添加主机 输入名称.群组和交换机IP(交换机要开启snmp) 2.创建监控项 输入OID和其它信息(键值随便填,但是不能和系统内的键值重复)OID获取方法可查看上一篇文章:http ...

  3. Fix: Unable to terminate process ‘Access is denied’ 杀进程,关服务

    https://appuals.com/fix-unable-to-terminate-process-access-is-denied/ 我 Process Hacker (方法3),成功杀掉: 阿 ...

  4. 剑指offer:调整数组顺序使奇数位于偶数前面

    题目 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分. 分析 事实上,这个题比较简单,很多种方式都可以实现,但是其时间复杂度或空间复 ...

  5. element-ui笔记

    1.el-dialog的关闭异常 在confirm按钮事件中,我们需要对业务参数进行校验,但是校验未通过,return false了,仍然关闭了弹窗. 原因:cancel按钮的click直接将弹窗的s ...

  6. 使用原生 JS 复制文本兼容移动端 iOS & android

    注意事项 使用 JS 实现复制功能并不是很难,但是有几个需要注意的地方. 首先文本只有选中才可以复制,所以简单的做法就是创建一个隐藏的 input,然后绑定需要复制的文本. 另外如果将 input 设 ...

  7. 四十二、在线预览pdf文件

    //文档在线观看 checkWoc(type, id, taskId, smsId, stsId) { if(type == "zip" || type == "7z&q ...

  8. maven笔记学习

    一.修改setting.xml文件中的镜像 在导入他人项目或者在导入项目时,我们会出现在项目中不能识别maven配置的库文件的情况那么我们可以重新下载本地库, 首先我们可以修改我们安装的maven环境 ...

  9. EXT 设置编辑框为只读

    Ext.getCmp("processResult").setReadOnly(ture);   //processResult是属性的id,setReadOnly(ture)设置 ...

  10. PS 怎么去掉图片上的文字

    第一步:打开需要去掉文字的图片. 第二步:在左侧工具栏中选择“吸管工具”. 第三步:在文字附近选取颜色. 第四步:在左侧工具栏中选择“矩形选框工具”,并选中要消除的文字. 第五步:在菜单栏“编辑”中选 ...