Search code examples
javajpaormspring-data-jpaquerydsl

Querydsl native jpa query return entities instead of object array


I'm using QueryDSL in my current project, and in one instance I need to use native query instead of jpa one due to jpql limitations.

Thankfully it's quite easy to swap from one to another and keep the api abstraction layer by just switching from JPAQuery to JPASQLQuery, however after I do that the jpa entities are no longer mapped as result type.

Example:

Using JPAQuery:

QPriceModel pm = QPriceModel.priceModel;

List<PriceModel> fetch = new JPAQuery<PriceModel>(entityManager)
    .select(pm)
    .from(pm)
    .fetch();

Will produce proper entities as result type:

enter image description here

But JPASQLQuery

QPriceModel pm = QPriceModel.priceModel;

List<PriceModel> fetch = new JPASQLQuery<PriceModel>(entityManager, new OracleTemplates())
    .select(pm)
    .from(pm)
    .fetch();

Will only return column arrays as is

results

Is there any way to force JPASQLQuery to return entities without manually mapping them?

Im using QUERY_DSL_VERSION=4.2.1


TLDR

Query dsl no longer maps jpa entities after switching from JPAQuery to JPASQLQuery


Solution

  • So it seems that JPASQLQuery does not use DefaultQueryHandler by default, which is needed to pass a type resolver to the entityManager as seen here https://github.com/querydsl/querydsl/blob/QUERYDSL_4_2_1/querydsl-jpa/src/main/java/com/querydsl/jpa/sql/AbstractJPASQLQuery.java#L105-L113

    My solution is to pass the DefaultQueryHandler to the constructor of the JPASQLQuery

    
            Configuration configuration = new Configuration(new OracleTemplates());
    
            new JPASQLQuery<>(entityManager, configuration,  DefaultQueryHandler.DEFAULT);
    

    This will produce a resolved entity from your select statement