0

I want to create a list of complex DTO objects with data from several Entities and one non-Entity-parameter. Let's say my DTO class has constructor:

public MyDto(String entityField, String someString) {...}

and I would like to use the CriteriaBuilder.construct method to create my list by doing like this:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<MyDto> query = builder.createQuery(MyDto.class);
Root<MyEntity> root = query.from(MyEntity.class);
builder.construct(MyDto.class, root.get("entityField"), someString);
...

but I am not allowed to do it, because the construct method wants from me only javax.persistence.criteria.Selection arguments.

The question: is there is a way to do it similar to this (at one blow) with Criteria API? Or I need to load MyEntity objects first and go through them and create a list of DTOs (not so pretty)?

golinko
  • 327
  • 2
  • 3
  • 14

1 Answers1

0

I use this approach each time I've a projection that collect fields from different entities or for privacy reason i must not return some data (for example passwords)

query.select(
    builder.construct(
      MyDto.class, 
      root.get("myfield"), // for field
      cb.literal(1), // for number
      cb.literal("blah blah")  // for string
));
Daniele Licitra
  • 1,520
  • 21
  • 45