Multiple columns in QueryDSL

16,572

Solution 1

EConstructor has been replaced with ConstructorExpression in Querydsl 2.0. So your example would become

List<CatDTO> catDTOs = query.from(cat)
    .list(ConstructorExpression.create(CatDTO.class, cat.id, cat.name));

You can also annotate the CatDTO constructor and query like this

List<CatDTO> catDTOs = query.from(cat)
    .list(new QCatDTO(cat.id, cat.name));

Alternatively you can use the QTuple projection which provides a more generic access option

List<Tuple> rows = query.from(cat)
    .list(new QTuple(cat.id, cat.name));

The actual values can be accessed via their path like this

tuple.get(cat.id)

and

tuple.get(cat.name)

Tuple projection will probably be used in Querydsl 3.0 for multiple columns projections instead of Object arrays.

Solution 2

using queryDSL 4 and Java 8 stream:

List<CatDTO> cats = new JPAQueryFactory(entityManager)
        .select(cat.id, cat.name)
        .from(cat)
        .fetch()
        .stream()
        .map(c -> new CatDTO(c.get(cat.id), c.get(cat.name)))
        .collect(Collectors.toList());
Share:
16,572
Gonçalo Cardoso
Author by

Gonçalo Cardoso

I'm an enthusiastic Java and C# programmer that loves to find solutions for hard problems. I always try to make the day-to-day job, simpler, easier and less error prone. Why complicate things when there's a simpler and working solution for each of them :)

Updated on June 23, 2022

Comments

  • Gonçalo Cardoso
    Gonçalo Cardoso almost 2 years

    I'm trying to get a list of multiple columns from my table using QueryDSL, and automatically fill my DB object, like this example in an older manual:

    List<CatDTO> catDTOs = query.from(cat)
        .list(EConstructor.create(CatDTO.class, cat.id, cat.name));
    

    The problem is that it looks like the EConstructor class was removed in version 2.2.0, and all the examples I find now are like this:

    List<Object[]> rows = query.from(cat)
        .list(cat.id, cat.name);
    

    Which forces me to manually cast all the objects into my CatDTO class.

    Is there any alternative to this? Any EConstructor alternative?

  • Gonçalo Cardoso
    Gonçalo Cardoso over 11 years
    So in either case (List<Object[]> or List<Tuple>) I need to manually assign each return object value to my CatDTO class?
  • Timo Westkämper
    Timo Westkämper over 11 years
    EConstructor is ConstructorExpression since 2.0, alternatively you can annotate the constructor of CatDTO with @QueryProjection and use new QCatDTO(...
  • Timo Westkämper
    Timo Westkämper over 11 years
    @balizeiro, do you need any other info?
  • Gonçalo Cardoso
    Gonçalo Cardoso over 11 years
    No, everything is ok. Thanks a lot