First problem is possible misunderstanding in usage of JPA entities as a query result. When entities are used as result of query, they mirror state of database. Replacing Employee.empName
with value other than one in database contradicts with that.
Until certain point that can be achieved via CriteriaBuilder.construct. Result objects (which can also be entities) are created via constructor which must take all the select items as an argument. Unfortunately that does not play well together with object graph (Project
and connected Employee
in this case).
Second problem is that in following get("employeeName")
is called for Project
, and it does not have such an attribute:
Root<Project> emp = c.from(Project.class);
...
coalesce.value(emp.<String>get("employeeName"));
In general coalesce can be used as follows (but because of what was said above, this does not alone solve problem):
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<String> c = cb.createQuery(String.class);
Root<Employee> emp = c.from(Employee.class);
CriteriaBuilder.Coalesce<String> coalesce = cb.coalesce();
coalesce.value(emp.<String>get("employeeName"));
coalesce.value("System Generated");
c.select(coalesce);
TypedQuery<String> q = em.createQuery(c);