spring-projects / spring-data-jpa

Simplifies the development of creating a JPA-based data access layer.
https://spring.io/projects/spring-data-jpa/
Apache License 2.0
3.03k stars 1.42k forks source link

Use of Projection with jpa specification executor #3657

Closed niyascode007 closed 3 weeks ago

niyascode007 commented 3 weeks ago

While creating the specification and trying to use the findBy method the hibernate query shows the result being fetched as the whole entity but the result is in mapped version of projection interface.

public Page<MessageProjection> testJpaSpecProjection(Pageable pageable, LocalDate fromDate, LocalDate toDate,
            String lrn, String mrn, String empfanger)
    {
        Specification<Message> spec = Specification.where(null);
        if (fromDate != null && toDate != null)
        {
            spec = spec.and((root, query, criteriaBuilder) -> criteriaBuilder.between(root.get("messageSentDate"),
                    fromDate.atStartOfDay().atOffset(ZoneOffset.UTC), toDate.atStartOfDay().atOffset(ZoneOffset.UTC)));
        }
        if (mrn != null && !mrn.isBlank())
        {
            spec = spec.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("MRN"), mrn));
        }
        if (lrn != null && !lrn.isBlank())
        {
            spec = spec.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("LRN"), lrn));
        }
        if (empfanger != null && !empfanger.isBlank())
        {
            spec = spec.and((root, query, criteriaBuilder) -> criteriaBuilder.equal(root.get("recipient"), empfanger));
        }
        return messageRepository.findBy(spec, q -> q.as(MessageProjection.class).page(pageable));
    }

    public interface MessageProjection
{
    String getMessageNumber();

    String getHandler();

    String getMRN();

}

@Repository
public interface MessageRepository extends JpaRepository<Message, String>, JpaSpecificationExecutor<Message>
{}
niyascode007 commented 3 weeks ago

using the projection it should only select those values from the DB it seems like the whole columns are being fetched and mapped to the projection .

mp911de commented 3 weeks ago

This is a duplicate and will be fixed via #2327/#3654