How to map TypedQuery result to custom object list

1.1k Views Asked by At

I need to make some select and map it to custom DTO

public class SomeClass {
    @PersistenceContext
    private EntityManager em;

    public void doSomething() {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<SomeClass2> criteria = builder.createQuery(SomeClass2.class);
        Root<SomeClass2> root = criteria.from(SomeClass2.class);
        Join<SomeClass3, SomeClass2> join = root.join("field");

        ... other joins and predicates ...

        em.createQuery(criteria);
    }
}

but

em.createQuery(criteria)
    .unwrap(org.hibernate.query.Query.class)
    .setResultTransformer(Transformers.aliasToBean(CustomDTO.class));

not helped.

I got an Exception

org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [net.package.api.SomeClass2]. 
Expected arguments are: java.lang.String, java.lang.String, Java.lang.String, long

Is this possible to map TypedQuery to some custom DTOs?

1

There are 1 best solutions below

1
On

DTO projections using a Constructor Expression and JPQL:

select new com.package.SomeDTO(p.id, p.title) from EntityCalss p