欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用SpringDataJPA開啟審計功能,自動保存操作人操作時間

 更新時間:2021年12月21日 11:26:54   作者:晴空排云  
這篇文章主要介紹了利用SpringDataJPA開啟審計功能,自動保存操作人操作時間,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

有些業(yè)務(wù)數(shù)據(jù)對數(shù)據(jù)的創(chuàng)建、最后更新時間以及創(chuàng)建、最后操作人進(jìn)行記錄。如果使用Spring Data Jpa做數(shù)據(jù)新增或更新,可實現(xiàn)自動保存這些信息而不需要顯示設(shè)置對應(yīng)字段的值,可通過以下步驟進(jìn)行配置。

1 相關(guān)注解

實現(xiàn)自動記錄上述信息主要有5個注解

  • @EnableJpaAuditing:審計功能開關(guān)
  • @CreatedBy:標(biāo)記數(shù)據(jù)創(chuàng)建者屬性
  • @LastModifiedBy:標(biāo)記數(shù)據(jù)最近一次修改者屬性
  • @CreatedDate:標(biāo)記數(shù)據(jù)創(chuàng)建日期屬性
  • @LastModifiedDate:標(biāo)記數(shù)據(jù)最近一次修改日期屬性

2 實現(xiàn)過程

2.1 依賴引用

使用Spring Data JPA要引用依賴spring-boot-starter-data-jpa,gradle引用方式如下

implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

2.2 實體類標(biāo)記審計屬性

案例使用User實體演示過程,需要在實體對應(yīng)的字段上添加對應(yīng)的注解表示是審計屬性,另外需要在實體類上開啟審計監(jiān)聽,如下:

@Entity
@Table(name = "h_user")
@EntityListeners({AuditingEntityListener.class})//開啟審計監(jiān)聽
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    //保存創(chuàng)建人的字段
    @CreatedBy
    @Column(name = "created_by")
    private String createdBy;
    //保存最近修改人的字段
    @LastModifiedBy
    @Column(name = "last_modified_by")
    private String lastModifiedBy;
    //保存創(chuàng)建時間的字段
    @CreatedDate
    @Column(name = "created_date")
    //保存最近修改日期的字段
    private Date createdDate;
    @LastModifiedDate
    @Column(name = "last_modified_date")
    private Date lastModifiedDate;
    private String realName;
    private String username;
    private String mobile;
    private String email;
    private String password;
    private Integer flag;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getCreatedBy() {
        return createdBy;
    }
    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }
    public String getLastModifiedBy() {
        return lastModifiedBy;
    }
    public void setLastModifiedBy(String lastModifiedBy) {
        this.lastModifiedBy = lastModifiedBy;
    }
    public Date getCreatedDate() {
        return createdDate;
    }
    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }
    public Date getLastModifiedDate() {
        return lastModifiedDate;
    }
    public void setLastModifiedDate(Date lastModifiedDate) {
        this.lastModifiedDate = lastModifiedDate;
    }
    
    public String getRealName() {
        return this.realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getMobile() {
        return mobile;
    }
    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @JsonIgnore
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getFlag() {
        return flag;
    }
    public void setFlag(Integer flag) {
        this.flag = flag;
    }
}

上述User實體對應(yīng)數(shù)據(jù)表定義如下:

create table h_user
(
 id int auto_increment primary key,
 username varchar(30) default '' not null comment '登錄用戶名',
 real_name varchar(30) default '' null comment '真實姓名',
 mobile varchar(25) default '' null comment '手機號碼',
 email varchar(30) default '' null comment '郵箱',
 password varchar(100) default '' null comment '加密密碼',
 flag int default '0' null comment '用戶標(biāo)記',
 created_by varchar(50) default 'HSystem' null comment '創(chuàng)建人',
 created_date datetime default CURRENT_TIMESTAMP not null,
 last_modified_by varchar(30) default 'HSystem' null comment '修改人',
 last_modified_date datetime default CURRENT_TIMESTAMP not null,
 constraint user_username_uindex unique (username)
)
engine=InnoDB;

2.3 審計自定義操作

當(dāng)對實體有新增或保存操作時,系統(tǒng)會自動獲取操作時的系統(tǒng)時間作為創(chuàng)建時間和修改時間。

對于創(chuàng)建者或最后修改這,審計過程會獲取當(dāng)前登錄系統(tǒng)的用戶信息,當(dāng)未登錄的情況下,需要指定默認(rèn)操作,可通過實現(xiàn)AuditorAware類來實現(xiàn)。

下面代碼在未獲取到用戶信息時返回HSystem表示默認(rèn)為系統(tǒng)操作。

@Configuration
public class SpringSecurityAuditorAware implements AuditorAware<String> {
    final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public Optional<String> getCurrentAuditor() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication instanceof AnonymousAuthenticationToken) {
                return Optional.of("HSystem");
            } else {
                if (authentication == null) {
                    return Optional.of("HSystem");
                }
                User user = (User) authentication.getPrincipal();
                return Optional.of(user.getUsername());
            }
        } catch (Exception ex) {
            logger.error("get user Authentication failed: " + ex.getMessage(), ex);
            return Optional.of("HSystem");
        }
    }
}

2.4 應(yīng)用開啟審計功能

在應(yīng)用程序入口類添加注解@EnableJpaAuditing開啟審計功能,如下

@SpringBootApplication
//啟用JPA審計功能,自動填充@CreateDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy注解的字段
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
public class HBackendApplication {
    public static void main(String[] args) {
        SpringApplication.run(HBackendApplication.class, args);
    }
}

注意:如果系統(tǒng)中有多個審計實現(xiàn),需要指定Bean的名稱,上面案例中使用名稱為springSecurityAuditorAware的bean。

2.5 實體操作

定義User實體類的JPA操作接口UserRepository如下

@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Integer>, JpaRepository<User, Integer> {
}

例如創(chuàng)建用戶時代碼如下,不需要顯示設(shè)置上面提到的4個屬性

User user = new User();
user.setUsername(username.trim());
user.setPassword(this.passwordEncoder.encode(password));
user.setEmail("crane.liu@qq.com");
user.setFlag(0);
user.setMobile("18988888888");
user.setRealName(username);
this.userRepository.save(user);

當(dāng)使用UserRepository對User類進(jìn)行保存時,系統(tǒng)會自動記錄數(shù)據(jù)的審計屬性值。

最終效果如下:

在這里插入圖片描述

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • java刪除數(shù)組中的某一個元素的方法

    java刪除數(shù)組中的某一個元素的方法

    下面小編就為大家?guī)硪黄猨ava刪除數(shù)組中的某一個元素的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • SpringBoot上傳臨時文件被刪除引起報錯的解決

    SpringBoot上傳臨時文件被刪除引起報錯的解決

    這篇文章主要介紹了SpringBoot上傳臨時文件被刪除引起報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • javax NotBlank和Email注解失效的解決

    javax NotBlank和Email注解失效的解決

    這篇文章主要介紹了javax NotBlank和Email注解失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • JAVA工程中引用本地jar的3種常用簡單方式

    JAVA工程中引用本地jar的3種常用簡單方式

    Jar文件的全稱是Java Archive File即Java歸檔文件,主要是對class文件進(jìn)行壓縮,是一種壓縮文件,和常見的zip壓縮文件兼容,下面這篇文章主要給大家介紹了關(guān)于JAVA工程中引用本地jar的3種常用簡單方式,需要的朋友可以參考下
    2024-03-03
  • SpringCloud學(xué)習(xí)筆記之Feign遠(yuǎn)程調(diào)用

    SpringCloud學(xué)習(xí)筆記之Feign遠(yuǎn)程調(diào)用

    Feign是一個聲明式的http客戶端。其作用就是幫助我們優(yōu)雅的實現(xiàn)http請求的發(fā)送。本文將具體為大家介紹一下Feign的遠(yuǎn)程調(diào)用,感興趣的可以了解一下
    2021-12-12
  • JAVA基礎(chǔ)之基本數(shù)據(jù)類型全面解析

    JAVA基礎(chǔ)之基本數(shù)據(jù)類型全面解析

    下面小編就為大家?guī)硪黄狫AVA基礎(chǔ)之基本數(shù)據(jù)類型全面解析。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-07-07
  • Java的回調(diào)機制實例詳解

    Java的回調(diào)機制實例詳解

    這篇文章主要介紹了Java的回調(diào)機制,結(jié)合實例形式詳細(xì)分析了java回調(diào)機制相關(guān)原理、用法及操作注意事項,需要的朋友可以參考下
    2019-08-08
  • 一篇文章帶你入門java網(wǎng)絡(luò)編程

    一篇文章帶你入門java網(wǎng)絡(luò)編程

    網(wǎng)絡(luò)編程是指編寫運行在多個設(shè)備(計算機)的程序,這些設(shè)備都通過網(wǎng)絡(luò)連接起來。本文介紹了一些網(wǎng)絡(luò)編程基礎(chǔ)的概念,并用Java來實現(xiàn)TCP和UDP的Socket的編程,來讓讀者更好的了解其原理
    2021-08-08
  • Spring Data JPA實現(xiàn)動態(tài)查詢的兩種方法

    Spring Data JPA實現(xiàn)動態(tài)查詢的兩種方法

    本篇文章主要介紹了Spring Data JPA實現(xiàn)動態(tài)查詢的兩種方法,具有一定的參考價值,有興趣的可以了解一下。
    2017-04-04
  • SpringBoot如何使用@RequestBody進(jìn)行數(shù)據(jù)校驗

    SpringBoot如何使用@RequestBody進(jìn)行數(shù)據(jù)校驗

    在Web開發(fā)中,前臺向后臺發(fā)送數(shù)據(jù)是非常常見的場景,而在SpringBoot框架中,我們通常使用@RequestBody注解來接收前臺發(fā)送的?JSON數(shù)據(jù),并將其轉(zhuǎn)化為Java對象,本文將介紹如何在?SpringBoot?中使用?@RequestBody?進(jìn)行數(shù)據(jù)校驗
    2023-06-06

最新評論