Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to automatically save the operation time of the operator by using the audit function enabled by SpringDataJPA

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to use SpringDataJPA to turn on the audit function to automatically save the operating time of the operator. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.

Some business data records the creation of the data, the last update time, as well as the creation and final operator. If you use Spring Data Jpa to add or update data, you can save the information automatically without displaying the values of the corresponding fields, which can be configured by the following steps.

1 there are 5 notes to realize automatic recording of the above information.

@ EnableJpaAuditing: audit function switch

@ CreatedBy: tag data creator attribute

@ LastModifiedBy: tag data last modified by attribute

@ CreatedDate: tag data creation date attribute

@ LastModifiedDate: tag data last modified date attribute

2 implementation process 2.1 dependent reference

To use Spring Data JPA, you need to refer to dependent spring-boot-starter-data-jpa,gradle references as follows

The implementation 'org.springframework.boot:spring-boot-starter-data-jpa'2.2 entity class marks audit attributes

The case uses User entities to demonstrate the process. You need to add a corresponding annotation to the corresponding field of the entity to indicate that it is an audit attribute. In addition, you need to enable audit monitoring on the entity class, as follows:

@ Entity@Table (name = "h_user") @ EntityListeners ({AuditingEntityListener.class}) / / turn on audit monitoring public class User {@ Id @ GeneratedValue (strategy = GenerationType.IDENTITY) private Integer id; / / Save the creator's field @ CreatedBy @ Column (name = "created_by") private String createdBy; / / Save the recently modified person's field @ LastModifiedBy @ Column (name = "last_modified_by") private String lastModifiedBy / / to save the field @ CreatedDate @ Column (name = "created_date") / / to save the field 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;}}

The data table corresponding to the above User entity is defined as follows:

Create table h_user (id int auto_increment primary key, username varchar (30) default''not null comment' login username', real_name varchar (30) default''null comment' Real name', mobile varchar (25) default''null comment' Mobile number', email varchar (30) default''null comment' mailbox', password varchar (100) default''null comment' encrypted password', flag int default'0' null comment 'user tag' Created_by varchar (50) default 'HSystem' null comment' founder, created_date datetime default CURRENT_TIMESTAMP not null, last_modified_by varchar (30) default 'HSystem' null comment' modifier', last_modified_date datetime default CURRENT_TIMESTAMP not null, constraint user_username_uindex unique (username)) engine=InnoDB 2.3 Audit Custom Action

When there is a new or save operation on an entity, the system automatically acquires the system time at the time of the operation as the creation time and modification time.

For the creator or the last modification of this, the audit process will obtain the user information of the current login system. When you are not logged in, you need to specify the default action, which can be achieved by implementing the AuditorAware class.

The following code returns HSystem when no user information is obtained, indicating that it defaults to the system operation.

@ Configurationpublic class SpringSecurityAuditorAware implements AuditorAware {final Logger logger = LoggerFactory.getLogger (this.getClass ()); @ Override public Optional 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 App enables audit function

Add the annotation @ EnableJpaAuditing to the application entry class to enable the audit function, as follows

@ SpringBootApplication// enables JPA audit, automatically populating @ CreateDate, @ CreatedBy, @ LastModifiedDate, @ LastModifiedBy annotated fields @ EnableJpaAuditing (auditorAwareRef = "springSecurityAuditorAware") public class HBackendApplication {public static void main (String [] args) {SpringApplication.run (HBackendApplication.class, args);}}

Note: if there are multiple audit implementations in the system, you need to specify the name of the Bean, and the bean named springSecurityAuditorAware is used in the above case.

2.5 physical operation

The JPA operation interface UserRepository that defines the User entity class is as follows

@ Repositorypublic interface UserRepository extends PagingAndSortingRepository, JpaRepository {}

For example, the time code for creating a user is as follows. There is no need to display the four attributes mentioned above.

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)

When the User class is saved using UserRepository, the audit property value of the data is automatically recorded.

The final effect is as follows:

After reading the above, do you have any further understanding of how to use SpringDataJPA to turn on the audit function to automatically save the operator's operating time? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report