Home > Enterprise >  QueryDSL, specify projection for join
QueryDSL, specify projection for join

Time:11-24

I'm trying to use QueryDSL to fetch a collection of entities (table Category) where each entity has a @OneToMany association with an other type of entity (table User), and a join is used to get it all in one go.

Problem is that the second entity (the users) contains CLOB fields which should not be included. I don't want to include them in my query. Given the following QueryDSL query :

JPAQuery<CategoryEntity> baseQuery = new JPAQuery<>(entityManager)
                .select(QCategoryEntity.categoryEntity)
                .from(QCategoryEntity.categoryEntity)
                .leftJoin(QCategoryEntity.categoryEntity.users, QUserEntity.userEntity)
                .where(somePredicate);

QueryDSL will generate something like

SELECT categoryen0_.id, (...), useren0_.id, (...) 
FROM category categoryen0 
LEFT OUTER JOIN user useren0 ON ...
WHERE ...

How can a specific projection be applied to this query such that the CLOB data is excluded?

Notes :

  • I'm trying to avoid native queries and changing the domain model.
  • I have not found a way to use Projections on the join itself.
  • Using subqueries inside joins is not supported by JPQL hence it's not supported by QueryDSL either.

CodePudding user response:

Turns out this was not working well due to my use of fetch joins, which prevented me from using projections. Solving it was a matter of using a basic join instead and manually reconstructing the relationship.

Collection<Tuple> tuples = new JPAQuery<>(entityManager)
                .select(QCategoryEntity.categoryEntity, Projections.constructor(UserEntity.class, <constructor arguments>)
                .from(QCategoryEntity.categoryEntity)
                .join(QCategoryEntity.categoryEntity.users, QUserEntity.userEntity)
                .where(somePredicate);
  • Related