@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy
在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的更多相关文章
- Spring JPA 使用@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy 自动生成时间和修改者
JPA Audit 在spring jpa中,支持在字段或者方法上进行注解@CreatedDate.@CreatedBy.@LastModifiedDate.@LastModifiedBy,从字面意思 ...
- js 获取input type="file" 选择的文件大小、文件名称、上次修改时间、类型等信息
文件名的传递 ---全路径获取 $('#file').change(function(){ $('#em').text($('#file').val()); }); 文件名的传递 ---只获取文件名 ...
- .NET 基础 一步步 一幕幕[面向对象之方法、方法的重载、方法的重写、方法的递归]
方法.方法的重载.方法的重写.方法的递归 方法: 将一堆代码进行重用的一种机制. 语法: [访问修饰符] 返回类型 <方法名>(参数列表){ 方法主体: } 返回值类型:如果不需要写返回值 ...
- JavaScript学习笔记(一)——延迟对象、跨域、模板引擎、弹出层、AJAX示例
一.AJAX示例 AJAX全称为“Asynchronous JavaScript And XML”(异步JavaScript和XML) 是指一种创建交互式网页应用的开发技术.改善用户体验,实现无刷新效 ...
- atitit.管理学三大定律:彼得原理、墨菲定律、帕金森定律
atitit.管理学三大定律:彼得原理.墨菲定律.帕金森定律 彼得原理(The Peter Principle) 1 彼得原理解决方案1 帕金森定律 2 如何理解墨菲定律2 彼得原理(The Pete ...
- 【完全开源】知乎日报UWP版(下篇):商店APP、github源码、功能说明。Windows APP 良心出品。
目录 说明 功能 截图+视频 关于源码和声明 说明 陆陆续续大概花了一个月的时间,APP算是基本完成了.12月份一直在外出差,在出差期间进行了两次功能完善,然后断断续续修补了一些bug,到目前为止,我 ...
- Windows Server 2012 磁盘管理之 简单卷、跨区卷、带区卷、镜像卷和RAID-5卷
今天给客户配置故障转移群集,在Windows Server 2012 R2的系统上,通过iSCSI连接上DELL的SAN存储后,在磁盘管理里面发现可以新建 简单卷.跨区卷.带区卷.镜像卷.RAID-5 ...
- react+redux教程(五)异步、单一state树结构、componentWillReceiveProps
今天,我们要讲解的是异步.单一state树结构.componentWillReceiveProps这三个知识点. 例子 这个例子是官方的例子,主要是从Reddit中请求新闻列表来显示,可以切换reac ...
- 记2016腾讯 TST 校招面试经历,电面、笔试写代码、技术面、hr面,共5轮
(出处:http://www.cnblogs.com/linguanh/) 前序: 距离 2016 腾讯 TST 校招面试结束已经5天了,3月27日至今,目前还在等待消息.从投简历到两轮电面,再到被 ...
随机推荐
- Python编码规范(PEP8)
Introduction 介绍 本文提供的Python代码编码规范基于Python主要发行版本的标准库.Python的C语言实现的C代码规范请查看相应的PEP指南1. 这篇文档以及PEP 257(文档 ...
- Datatables插件1.10.15版本服务器处理模式ajax获取分页数据实例解析
一.问题描述 前端需要使用表格来展示数据,找了一些插件,最后确定使用dataTables组件来做. 后端的分页接口已经写好了,不能修改.接口需要传入页码(pageNumber)和页面显示数据条数(pa ...
- maven build pulgin
<build> <defaultGoal>compile</defaultGoal> <plugins> <!-- 生成清单文件相关 --> ...
- sklearn保存模型-【老鱼学sklearn】
训练好了一个Model 以后总需要保存和再次预测, 所以保存和读取我们的sklearn model也是同样重要的一步. 比如,我们根据房源样本数据训练了一下房价模型,当用户输入自己的房子后,我们就需要 ...
- Windows10 永久激活查询/激活时间查询/激活查询命令/激活码查询
1.使用 Windows + R组合快捷键打开运行命令框 运行: slmgr.vbs -dlv 命令 可以查询到Win10的激活信息,包括:激活ID.安装ID.激活截止日期等信息.看不懂的 ...
- 3.RNN推导
1.基本RNN结构 这几天想入门NLP,所以开始了解RNN以及一系列变体.首先RNN最原始的结构如下图(图是按自己的理解用visio画的,有错麻烦提一下), 首先我们来说明一下各个符号的定义: 各个变 ...
- hdu5701-中位数计数
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5701 题目: Problem Description 中位数定义为所有值从小到大排序后排在正中间的那个 ...
- ISP PIPLINE (附加1) Green Imbalance
1.什么是Green imbalance 芯片的Gr和Gb通道获取的能量或者是输出的数据不一致,造成这种情况的原因一方面是Gr,Gb通道的半导体制造工艺方面的差异,另一方面是microlens的存在, ...
- python 字符串常用操作
字符串常用方法 capitalize() String.capitalize() 将字符串首字母变为大写 name = 'xiaoming' new_name = name.capitalize() ...
- python底层原理
有同学问到了一个问题,python中存储变量是通过内存地址来存储,那么python又是如何去判断内存中的地址是什么数据类型的呢.经过查找,找到这篇文章: 原博客地址:http://www.cnblog ...