Multiple Columns in QueryDSL

I am trying to get a list of several columns from my table using QueryDSL and automatically populate 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 that I have found now look like this:

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

This forces me to manually map all objects to my CatDTO class.

Is there an alternative to this? Any alternative to EConstructor?

+5
source share
3 answers

EConstructor has been replaced by the ConstructorExpression expression in Querydsl 2.0. So your example will become

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

You can also annotate the CatDTO constructor and request this

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

QTuple,

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

tuple.get(cat.id)

tuple.get(cat.name)

Tuple, , Querydsl 3.0 .

+6

queryDSL 4 Java 8:

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());
0

Another alternative is to use a class Projections. It will build the object using fields that you pass as parameters, for example EConstructor. Example:

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

Link: http://www.querydsl.com/static/querydsl/4.0.5/apidocs/com/querydsl/core/types/Projections.html

0
source

All Articles