anthofo
anthofo

Reputation: 93

Hibernate JPQL Constructor Expression doesn't work with OneToMany field

When I try to use a constructor expression in a JPQL query

class CompanyProjection {
    String name;
    List<Employee> employees;

    public CompanyProjection (String name, List<Employee> employees) {
        ...
    }    
}

class Company {
    String name;

    @OneToMany(mappedBy = "company")
    List<Employee> employees;
}

class Employee {
     @ManyToOne
     Company company;
}

select com.foo.CompanyProjection(c.name, c.employees) from Company c

I get a org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.foo.CompanyProjection]. Expected arguments are: java.lang.String, com.foo.Employee[........]

From the stacktrace above, I understand that Hibernate expects the second constructor argument to have an Employee.class type instead of the List.class.

But c.employees is actually a List. I don't understand if it is a bug in hibernate, or if I'm misusing it?

Upvotes: 1

Views: 568

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

User error.

Using multi-valued fields in a SELECT clause of JPQL is ILLEGAL syntax. See the JPQL BNF.

Upvotes: 1

Related Questions