51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1620|回复: 0
打印 上一主题 下一主题

[原创] springboot 中用注解生成审计(Auditing)字段。如:@LastModifiedBy

[复制链接]

该用户从未签到

跳转到指定楼层
1#
发表于 2019-3-18 17:19:09 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

在spring jpa中,支持在字段或者方法上进行注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy。维护数据库的创建时间、创建人、最后修改时间、最后修改人。实现步骤如下:

一、在需要的实体上做下面的改造。
  • 在实体类上使用注解。@EntityListeners。
  • 在响应的字段属性上加注解。如:@LastModifiedDate
  1. @MappedSuperclass
  2. @EntityListeners(AuditingEntityListener.class)
  3. public class BaseEntity {
  4.         private static final long serialVersionUID = 7491626901163891174L;
  5.         @Id
  6.         @GeneratedValue(strategy = GenerationType.IDENTITY)
  7.         private Long id;

  8.         @JsonIgnore
  9.         @Temporal(TemporalType.TIMESTAMP)
  10.         @CreatedDate
  11.         @Column(updatable = false)
  12.         private Date createTime;

  13.         @JsonIgnore
  14.         @Temporal(TemporalType.TIMESTAMP)
  15.         @LastModifiedDate
  16.         @Column(updatable = false)
  17.         private Date updateTime;

  18.         @LastModifiedBy
  19.         private String updatedBy;
  20.         //省略getter、setter
复制代码
二、增加AuditorAware实现类。用于获取创建人、最后修改人。
  1. @Component("auditorAware")
  2. public class AuditorAwareImpl implements AuditorAware<String> {

  3.     @Override
  4.     public Optional<String> getCurrentAuditor() {
  5.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  6.         return Optional.of(authentication.getPrincipal().toString());
  7.     }
  8. }
复制代码
三、在springbooot入口类上配置@EnableJpaAuditing。
  1. @SpringBootApplication
  2. @EnableCaching(proxyTargetClass = true)
  3. @EnableJpaAuditing(auditorAwareRef = "auditorAware")
  4. public class TestApplication {
  5. }
复制代码

其中的auditorAwareRef = "auditorAware"就是上面配置的@Component("auditorAware")






分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

本版积分规则

关闭

站长推荐上一条 /1 下一条

小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

GMT+8, 2024-5-5 12:13 , Processed in 0.063071 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2024 Comsenz Inc.

快速回复 返回顶部 返回列表