ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2023년 1월 6일
    Today I Learned 2023. 1. 6. 23:15

    JPA Specification

    JpaSpecificationExecutor

    // repositories/PlaceRepository.java
    
    public interface PlaceRepository
        extends JpaRepository<Place, Long>, JpaSpecificationExecutor<Place> {
        Optional<Place> findByInformationName(String placeName);
    }

     

     

    Specification 객체

    // specifications/PlaceSpecification.java
    
    public class PlaceSpecification {
        public static Specification<Place> likeInformationName(
            String informationName
        ) {
            return new Specification<Place>() {
                @Override
                public Predicate toPredicate(Root<Place> root,
                                             CriteriaQuery<?> query,
                                             CriteriaBuilder criteriaBuilder) {
                    return criteriaBuilder.like(
                        root.get("information")
                        	.get("name"),
                        "%" + informationName + "%");
                }
            };
            
            // return (root, query, criteriaBuilder) -> criteriaBuilder.like(
            //     root.get("information")
            //         .get("name"),
             //    "%" + keyword + "%");
        }
    }

     

    Service

    // services/SearchPlacesService.java
    
    public class SearchPlacesService {
        private final PlaceRepository placeRepository;
    
        public SearchPlacesService(PlaceRepository placeRepository) {
            this.placeRepository = placeRepository;
        }
    
        public PlaceSearchResultsDto searchPlaces(String keyword) {
            Specification<Place> specification
                = Specification.where(PlaceSpecification.likeInformationName(keyword));
    
            List<PlaceSearchResultDto> placeSearchResultDtos
                = placeRepository.findAll(specification)
                .stream()
                .map(Place::toSearchResultDto)
                .toList();
    
            return new PlaceSearchResultsDto(placeSearchResultDtos);
        }
    }

     

    References

    - root.get: https://dev-setung.tistory.com/20

     

     

     

     

    array.splice() vs array.slice()

    splice는 원본 배열을 변경 >> 원본 배열에 가변

    slice는 새로운 배열을 생성해 변경 >> 원본 배열은 불변

    아직 직접 검증하지 않음

     

     

     

    댓글

Designed by Tistory.