Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple columns in QueryDSL

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?

like image 801
Gonçalo Cardoso Avatar asked Sep 14 '12 15:09

Gonçalo Cardoso


1 Answers

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.

like image 159
Timo Westkämper Avatar answered Oct 06 '22 01:10

Timo Westkämper