java—如何在SpringBoot中使用enver在审计表中添加字段

y53ybaqx  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(507)

早上好,如何在审核表中添加字段?
我需要审核一些表,但我需要找到执行操作的用户。我的被审计单位是:

@Entity
@Table(name ="TableName")
@Audited
@AuditTable("TableNameAuditedLog")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "myId")
    private Long id;

    @Column(name = "myName")
    private String name;
}

查看文档时,我看到了一个示例,一个自定义类将成为我的审核和侦听器,因此我这样做:

@Data
@RevisionEntity(AuditListener.class)
@MappedSuperclass
public class Audit {

    @Id
    @GeneratedValue
    @RevisionNumber
    private Long id;

    @RevisionTimestamp
    private Long timestamp;

    @Column(name = "user")
    private String user;
}

public class AuditListener implements RevisionListener {

    @Override
    public void newRevision(Object revisionEntity) {
        Audit audit = (Audit) revisionEntity;
        audit.setUsuario("user");
    }
}

我尝试在实体类中扩展audit类,但jpa有问题,问题是:

Caused by: org.hibernate.MappingException: Unable to find column with logical name: myId in org.hibernate.mapping.Table(TableNameAuditedLog) and its related supertables and secondary tables

我该怎么做?
谢谢大家。

pqwbnv8z

pqwbnv8z1#

从审计类中删除mappedsuperclass。您还可以使用audit extend defaultrevisionentity。在audit类中,您只需要自定义字段。

@Column(name = "user")
private String user;

自定义审核修订实体:

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@RevisionEntity(UserRevisionListener.class)
public class AuditRevisionEntity extends DefaultTrackingModifiedEntitiesRevisionEntity {
  private static final long serialVersionUID = 1L;

  private Long userId;

  @Column(length = 100, nullable = false)
  private String initiator;
}

和修订侦听器

public class UserRevisionListener implements RevisionListener {
  private static final String SYSTEM_USER = "System";
  private transient final SecurityUtils securityUtils;

  public UserRevisionListener(final SecurityUtils securityUtils) {
    this.securityUtils = securityUtils;
  }

  @Override
  public void newRevision(Object revisionEntity) {
    final AuditRevisionEntity are = (AuditRevisionEntity) revisionEntity;

    securityUtils.getPrincipal().ifPresentOrElse((appPrincipal) -> {
      are.setUserId(appPrincipal.getUserId());
      are.setInitiator(appPrincipal.getDisplayName());
    }, () -> are.setInitiator(SYSTEM_USER));
  }
}

在我的例子中,我使用securityutils助手获取当前主体(我使用具有额外字段的自定义主体),并根据需要设置auditrevisionentity。有些更改是由quartz作业进行的,因此没有主体,在这种情况下,只设置了启动器。

相关问题