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.

  1. Apply the ‘@EnableJpaAuditing’ annotation to the Spring Boot application
  2. 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’
  3. 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;
    }

 Query method functionality

 

1. Parameter Binding

Parameter binding refer to the process of assigning input values to the parameters in a query. In Spring Data JPA, We could bind paramter by 2 ways.
And it allow us to pass a collection of values as a parameter to a query method

  • Position-based : Assigning values based on their order
  • Name-based : Assigning values basen on parameter names

Example

select m from Member m where m.username = ?0 //Postition-based

select m from Member m where m.username = :name //Name-based

@Query("select m from Member m where m.username in :names")
List<Member> findByNames(@Param("names") List<String> names); //Collection parameter binding

 

2. Return Type

In Spring Data JPA, the return type of a query method specifies the type of the data that will be return from the database query. The return type can be entity object or a collection of entity objects.

 

Example

Person findByLastName(String lastName); // Return an object

List<Book> findByCategory(String category); // Return a collection of entities

Optional<Member> findByUsername(String name); // Return an object wrapped by Optional Class

 

 

3. Paging and Sorting

Spring Data JPA also support paging and sorting. And these two important features of Spring Data JPA allow developers to handle larget dataset efficiently. Spring Data JPA provides built-in support for paging, which can be enabled by defining a 'Pageable' argument in the repository method signature. The Pageable interface allows specifying the desired number of results per page, the page size, and the sorting criteria.

 

Page<Member> findByUsername(String name, Pageable pageable); //count query

Slice<Member> findByUsername(String name, Pageable pageable); //no count query

List<Member> findByUsername(String name, Pageable pageable); //no count query

List<Member> findByUsername(String name, Sort sort);

 

To use this method, you could create a PageRequest object that specifies the desired page number, the page size, and the sort criteria:

 

Basic explanation about PageRequest

PageRequest pageRequest = PageRequest.of(0, 3, Sort.by(Sort.Direction.DESC,"username"));

Page<Member> page = memberRepository.findByAge(10, pageRequest);

Caution : Page start from the value of '0' not '1'

 

And the Page class has some useful static methods in it. 

  • getTotalElement(): Returns the total number of elements in a Page instance.
  • getNumber(): Returns the current page number.
  • getTotalPages(): Returns the total number of pages.
  • isFirst(): Returns a boolean value indicating whether the current page is the first page.
  • hasNext(): Returns a boolean value indicating whether there is a next page available

공통인터페이스 생성(by Spring Data JPA 김영한선생님)

Spring Data JPA가 제공하는 공통인터페이스?

Spring Data JPA는 순수 JPA로 구현한 ImplementedJpaRepository 가 아닌, Spring Data JPA가 제공하는 공통 인터페이스만을 사용함으로써 똑같은 기능을 얻을 수 있다.

 

사용방법

public interface MemberRespository extends JpaRespository<Member, Long>{
}
  • JpaRepository 인터페이스 : 공통 CRUD 제공(Create, Read, Update, Delete)
  • 제네릭은 <Entity Type, Identifier Type> 으로 설정

이렇게 임의로 만든 MemberRepository가 JpaRepository를 상속받으면 그 자체로 공통인터페이스가 된다!

It's kinda a magic! isn't it?

 

공통 인터페이스 구성

사진출처 : SpringDataJPA 김영한선생님 자료

  • Spring Data JPA는 Spring Data가 가지고있는 CurdRepository, PagingAndSortingRepository를 상속받고 있음을 알 수 있다.
  • PagingAndSortingRepository를 상속한다는 의미는 페이징과 정렬을 JpaRepository에서 사용할 수 있음을 유추할 수 있다.
  • 제네릭 타입
    • T : Entity
    • ID: Identifier Type of Entity
    • S: Type of Entity and it's subclass

 

쿼리 메소드 기능

1. Query Creation by naming method's name

  • 공통 인터페이스에 이름을 규칙에 따라 정의함으로써 JPQL쿼리가 자동적으로 실행하게 함.
  • 단순하지만 자주 반복되는 쿼리에 관해 간단히 쿼리를 작성가능 하도록 한다.
  • 예시
interface PersonRepository extends Repository<Person, Long> {

  List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);

  // Enables the distinct flag for the query
  List<Person> findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname);
  List<Person> findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname);

  // Enabling ignoring case for an individual property
  List<Person> findByLastnameIgnoreCase(String lastname);
  // Enabling ignoring case for all suitable properties
  List<Person> findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname);

  // Enabling static ORDER BY for a query
  List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
  List<Person> findByLastnameOrderByFirstnameDesc(String lastname);
}

2. NamedQuery

  • @NamedQuery어노테이션을 이용해, NamedQuery를 미리 정의해두고 호출하는 방식
  • 예시
@Query(name = "Member.findByUsername")
List<Member> findByUsername(@Param("username") String username);

public interface MemberRepository
extends JpaRepository<Member, Long> { //** Member Domain Class
List<Member> findByUsername(@Param("username") String username);
}
  • 스프링 데이터 JPA는 선언한 "도메인 클래스 + .(점) + 메서드 이름"으로 Named 쿼리를 찾아서 실행
  • 권장되는 방법이 아님.

3. @Query - query defining on Repository's method

  • 쿼리 메소드 기능 중에서, Custom이 필요할 때, 개인적으로 선호하는 방식
  • JPQL 쿼리를 @Query의 Attribute로 직접 작성
  • 예시
//1번 예시.
public interface MemberRepository extends JpaRepository<Member, Long> {
@Query("select m from Member m where m.username= :username and m.age = :age")
List<Member> findUser(@Param("username") String username, @Param("age") int
age);
}

//2번 예시.
//단순히 값 하나를 조회
@Query("select m.username from Member m")
List<String> findUsernameList();

//3번 예시.
//DTO 조회
@Query("select new study.datajpa.dto.MemberDto(m.id, m.username, t.name) " +
"from Member m join m.team t")
List<MemberDto> findMemberDto();

 

//== 이후 추가 수정 예정 ==//

4. Parameter Binding

5. Return Type

6. Paging and Sorting

7. Bulk Upadate Query

8. @Entity Graph

'Spring Data JPA' 카테고리의 다른 글

Auditing and Web extension of Paging and Sorting  (0) 2023.03.19
#2. Spring Data Jpa: Query method 2  (0) 2023.03.14

+ Recent posts