1. Auditing
01. What is Auditing?
In Spring Data JPA, Auditing refer to the process of automatically capturing and sharing metadata related to the changes made to the entities in a database. This metadata includes information such as when an entity created or modified, and by whom.
Auditing is accomplished using Spring Data JPA’s built-in support for auditing. When enabled, Spring Data JPA automatically populate the auditing fields of an entity with the appropriate metadata, using annotation such as ‘@CreatedDate’ , ‘@LastModifiedDate’,’@CreatedBy’, and ‘@LastModifiedBy’
02. Apply Auditing into my project.
The following steps can be followd to apply Auditing in a Spring Boot project.
- Apply the ‘@EnableJpaAuditing’ annotation to the Spring Boot application
- Then, apply '@EntityListeners(AuditingEntityListener.class)’ to every entity class that you want to use Auditing on. +Tips! ‘BaseEntity’ is usually inherited from other entities, so don’t forget to use the ‘@MappedSuperclass’
- Use the appropriate annotations for the fields in the entity based on your purpose. The availble annotations are
- @CreatedBy
- @LastModifiedBy
- @CreatedDate
- @LastModifiedDate
03. Example
@MappedSuperclass
@Getter
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
}
2. Web extesion of Paging and Sorting.
01. What it means that?
Spring Data offers Paging and Sorting functionality that can be used with Spring MVC.
- The Pageable interface can be used as a parameter in MVC methods.
- Pageable is an interface that is automatically implemented by the PageRequest class.
02. Request Parameters
- Example: /members?page=0&size=3&sort=id,desc&sort=username,desc
- Default values:
- size = 20
- page = 2000
03. Default Settings
- Global settings:
- Modify Pageable values in properties.
- Modifying values for specific cases:
- Apply the @PageableDefault annotation to the Pageable parameter.
- Modify the attribute value.
04. Prefix
- Use prefixes to differentiate paging information when there are more than two pageable objects.
- Apply the @Qualifier("STH") annotation and indicate which entity name to use.
05. DTO Conversion from Page Content
- Entities should always be converted to DTOs. Exposing entities directly through APIs can cause issues.
- Use map() to handle inner data with Page.
06. Example
@GetMapping("/members2")
public Page<MemberDto> list(Pageable pageable) {
Page<Member> page = memberRepository.findAll(pageable);
Page<MemberDto> map = page.map(member -> new MemberDto(member.getId(), member.getUsername()));
return map;
}
'Spring Data JPA' 카테고리의 다른 글
#2. Spring Data Jpa: Query method 2 (0) | 2023.03.14 |
---|---|
#1. Spring Data JPA 공통인터페이스, Query Method (0) | 2023.03.13 |