특정 조건에서 해당하는 엔티티가 존재하는 경우 삭제 진행하는 코드. (JPA)
일반적인 람다 표현식으로 작성하면 아래와 같다.
testRepository.findBytestId(testId)
.ifPresent(testEntity -> {
testRepository.delete(testEntity);
});
축약해서 아래와 같이 표현 가능. (기능은 동일)
testRepository.findBytestId(testId)
.ifPresent(testRepository::delete);
=> Java의 메서드 레퍼런스를 활용하여 불필요한 매개변수 생략 가능.
메서드 참조 (Method Reference)
람다식을 활용해 메서드를 호출 할 때 :: 연산자를 사용한 축약 문법.
// 람다식 호출
x -> someMethod(x)
// 메서드 참조 (축약)
SomeClass::someMethod
단, 입력 매개변수와 반환 타입이 함수형 인터페이스와 일치해야 한다.
( 매개변수 → 메서드 호출 구조가 같을 때 사용 가능, 컴파일러의 데이터 타입 추론이 가능해야 함. )
* static 메서드 참조
Function<String, Integer> func = s -> Integer.parseInt(s);
Function<String, Integer> func2 = Integer::parseInt;
* 특정 객체의 인스턴스 메서드 참조
Consumer<String> printer = s -> System.out.println(s);
Consumer<String> printer2 = System.out::println;
* 특정 타입의 임의 객체 메서드 참조
Function<String, String> f = s -> s.toLowerCase();
Function<String, String> f2 = String::toLowerCase;
* 생성자 참조
Supplier<List<String>> supplier = () -> new ArrayList<>();
Supplier<List<String>> supplier2 = ArrayList::new;
'Java > JPA' 카테고리의 다른 글
| [JPA] Querydsl 벌크삭제 (2) (0) | 2025.01.27 |
|---|---|
| [JPA] 네이티브 쿼리 (조건문) + 오류 (0) | 2024.10.12 |
| [JPA] findBy~ 일부 필드값만 가져오기 (JPQL, 네이티브쿼리) / (+ 오류) (0) | 2024.07.28 |
| [JPA] JPA_existBy~ / Querydsl 성능비교 (+ fetchOne(), fetchFirst()) (0) | 2024.06.21 |
| [JPA] List<Entity> 비교 (0) | 2024.06.19 |