在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);
}

@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy的更多相关文章

  1. Spring JPA 使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 自动生成时间和修改者

    JPA Audit 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate.@CreatedBy.@LastModifiedDate.@LastModifiedBy,从字面意思 ...

  2. js 获取input type="file" 选择的文件大小、文件名称、上次修改时间、类型等信息

    文件名的传递 ---全路径获取 $('#file').change(function(){ $('#em').text($('#file').val()); }); 文件名的传递 ---只获取文件名 ...

  3. .NET 基础 一步步 一幕幕[面向对象之方法、方法的重载、方法的重写、方法的递归]

    方法.方法的重载.方法的重写.方法的递归 方法: 将一堆代码进行重用的一种机制. 语法: [访问修饰符] 返回类型 <方法名>(参数列表){ 方法主体: } 返回值类型:如果不需要写返回值 ...

  4. JavaScript学习笔记(一)——延迟对象、跨域、模板引擎、弹出层、AJAX示例

    一.AJAX示例 AJAX全称为“Asynchronous JavaScript And XML”(异步JavaScript和XML) 是指一种创建交互式网页应用的开发技术.改善用户体验,实现无刷新效 ...

  5. atitit.管理学三大定律:彼得原理、墨菲定律、帕金森定律

    atitit.管理学三大定律:彼得原理.墨菲定律.帕金森定律 彼得原理(The Peter Principle) 1 彼得原理解决方案1 帕金森定律 2 如何理解墨菲定律2 彼得原理(The Pete ...

  6. 【完全开源】知乎日报UWP版(下篇):商店APP、github源码、功能说明。Windows APP 良心出品。

    目录 说明 功能 截图+视频 关于源码和声明 说明 陆陆续续大概花了一个月的时间,APP算是基本完成了.12月份一直在外出差,在出差期间进行了两次功能完善,然后断断续续修补了一些bug,到目前为止,我 ...

  7. Windows Server 2012 磁盘管理之 简单卷、跨区卷、带区卷、镜像卷和RAID-5卷

    今天给客户配置故障转移群集,在Windows Server 2012 R2的系统上,通过iSCSI连接上DELL的SAN存储后,在磁盘管理里面发现可以新建 简单卷.跨区卷.带区卷.镜像卷.RAID-5 ...

  8. react+redux教程(五)异步、单一state树结构、componentWillReceiveProps

    今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...

  9. 记2016腾讯 TST 校招面试经历,电面、笔试写代码、技术面、hr面,共5轮

    (出处:http://www.cnblogs.com/linguanh/) 前序: 距离  2016 腾讯 TST 校招面试结束已经5天了,3月27日至今,目前还在等待消息.从投简历到两轮电面,再到被 ...

随机推荐

  1. Django—模型

    索引 1.定义模型类 2.模型类 3.字段查询 4.查询集 5.模型类关系 6.模型类扩展 ORM简介 ORM,全拼Object-Relation Mapping,中文意为对象-关系映射,是随着面向对 ...

  2. js编码解码 punyCode

    ;(function(w) { var PunycodeModule = function () { function IdnMapping() { this.utf16 = { decode: fu ...

  3. requests之headers 'Content-Type': 'text/html'误判encoding为'ISO-8859-1'导致中文text解码错误

    0. requests不设置UA 访问baidu 得到 r.headers['Content-Type'] 是text/html  使用chrome UA: Content-Type:text/htm ...

  4. SSH项目需要的所有架包

    原地址:https://blog.csdn.net/qq_35816104/article/details/54346182   SSH框架:struts2 hibernate spring 该三大框 ...

  5. pycharm中连接公网IP方法

    我们的公网IP可以加到pycharm里面,这样程序跑的时候,在测试过程中就用pycharm直接修改文件,然后在pycharm里面上传,操作更加便捷 在pycharm中找到tool按钮,在菜单栏里面 然 ...

  6. debian安装mongoDB

    wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.8.2.tgz tar zxf mongodb-linux-i686-1.8.2.t ...

  7. web理论知识--网页访问过程(附有Django的web项目访问流程)

    当我们闲暇之余想上网看看新闻,或者看个电影,通常的操作是:打开电脑.打开浏览器.输入网址.浏览页面信息.点击自己感兴趣的连接......那么有没有想过,这些网页从哪里来的?过程中计算机又做了什么事情了 ...

  8. [wordpress]更新插件时,免去FTP操作

    我们先进入服务器 先找到wordpress配置文件wp-config.php,用locate命令寻找文件所在路径. sudo updatedb locate wp-config.php 然后cd到改路 ...

  9. es6中的...三个点

    ...是es6中新添加的操作符,可以称为spread或rest 定义一个数组 let name=['小红','小明','小白']; 我们在控制台输出   console.log(name); 结果: ...

  10. Laravel安装redis扩展

    Laravel安装redis扩展 1.使用命令行,执行(当然要先安装composer) composer require predis/predis 2.执行完就安装好了,redis相关配置可以到.e ...