@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日至今,目前还在等待消息.从投简历到两轮电面,再到被 ...
随机推荐
- vertx实例的fileSystem文件系统模块
初始化 //根据OS区分实现 System.getProperty("os.name").toLowerCase(); Utils.isWindows() ? new Window ...
- SpringBoot webmvc项目导出war包并在外部tomcat运行产生的诸多问题以及解决方案
背景: 有需求要将原来的Spring(3.2.6) + Springmvc + Hibernate项目重构为Springboot(1.5.2)项目 描述: 记录重构过程,以及期间遇到的种种问题和对应的 ...
- .net core web api 与httpclient发送和接收文件及数据
客户端 HttpClient var url = $"https://localhost:44323/api/values/posttest?resource_source=yangwwme ...
- Android 基础一 TextView,Style样式,Activity 传值,选择CheckBox 显示密码
1.修改TextView字体 mTextView = (TextView) findViewById(R.id.textview1); mTextView.setText("I am her ...
- ABP给WebApi添加性能分析组件Miniprofiler
在ABP的WebApi中,对其性能进行分析监测是很有必要的.而悲剧的是,MVC项目中可以使用的MiniProfiler或Glimpse等,这些都不支持WebApi项目,而且WebApi项目通常也没有界 ...
- 03.Regression
01.regression # -*- coding: utf-8 -*- """ scipy 패키지 선형 회귀분석 """ from s ...
- 批量导出hive表的建表语句
转的这里的 首先先导出所有的table表 hive -e "use xxxdb;show tables;" > tables.txt 然后再使用hive内置语法导出hive表 ...
- 解决Mysql命令行输入密码闪退问题
输入密码闪退是因为后台Mysql服务没有启动. 解决办法:我的电脑,右键管理,服务,查看服务里面Mysql是否在运行.如果没有在运行那么可以右键启动,最好属性中设置为自动启动.
- 【spring】-- 手写一个最简单的IOC框架
1.什么是springIOC IOC就是把每一个bean(实体类)与bean(实体了)之间的关系交给第三方容器进行管理. 如果我们手写一个最最简单的IOC,最终效果是怎样呢? xml配置: <b ...
- Huginn定时时间不准确或延后问题
碰巧遇到的:Huginn定时为每天晚上九点执行的任务,却在午后1点执行了, 查了下,午后一点,正好是太平洋时间前一天的晚上9点,一开始没考虑到,午后调试程序,它莫名其妙执行了一次,才发现问题, 那就换 ...