Skip to content

Use of Projection with jpa specification executor #3657

@niyascode007

Description

@niyascode007

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>
{}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions