Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA query using specification and projection

I used spring jpa specification to build dynamically an entity query.

It's working perfect but the query returns all entity fields which makes the performance slower. I want to fetch specific entity fields only and not fetching all entity fields and dependencies which I don't want and I will not use.

I search on the web, I tried some scenarios but without any lack. Can anyone suggest any solution on this?

Thanks in advance

Here is what I have.I'm using spring boot 2.2.4

public class Concert {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @Column
    private String code;

    @Column
    private double totalIncome;

    @Column            
    private double totalExpenses;

    @Column
    private double totalBudget;

    @ManyToOne(targetEntity = Orchestra.class, fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "orchestra_id")
    private Orchestra orchestra;

    @ManyToOne(targetEntity = ConcertStatus.class, fetch = FetchType.EAGER, optional = false)
    @JoinColumn(name = "concert_status_id")
    private ConcertStatus status;

    /* other fields */

}

Specification:

public class ConcertSpecification implements Specification<Concert> {

    @Override
    public Predicate toPredicate(Root<Concert> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
        List<Predicate> predicates = new ArrayList<>();

        //add add criteria to predicates
        for (Criterion criteria : criteriaList) {

            /* predicates builder here */
        }

        return builder.and(predicates.toArray(new Predicate[0]));
    }
}

Repository:

public interface ConcertDao extends JpaRepository<Concert, Long>, JpaSpecificationExecutor<Concert>, PagingAndSortingRepository<Concert, Long> { }

ConcertService:

public interface ConcertService {
    Page<Concert> findAll(@Nullable Specification<Concert> spec, Pageable pageable); 
}   

ConcertServiceImpl:

@Service(value = "concertService")
public class ConcertServiceImpl implements ConcertService {

    public Page<Concert> findAll(@Nullable Specification<Concert> spec, Pageable pageable){
        List<Concert> list = new ArrayList<>();
        concertDao.findAll(spec).iterator().forEachRemaining(list::add);
        return new PageImpl<Concert>(list);
    }
}   
like image 999
Bad_Pan Avatar asked Sep 06 '25 02:09

Bad_Pan


1 Answers

Usage of projections with specifications are not supported and there is a PR for it that has been hanging for over five years.

like image 74
rozeus Avatar answered Sep 07 '25 23:09

rozeus