I have the following java
code that uses hibernate
predicates to return search reusults from my Appointment MYSQL
table.
public List<Appointment> getSearchResults(String client, AppointmentSearchRequest searchRequest, Predicate completePredicate) {
List<Appointment> searchResults = new ArrayList<>();
EntityManager entityManager = null;
try {
entityManager = entityManagement.createEntityManager(client);
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Appointment> query = builder.createQuery(Appointment.class);
Root<Appointment> from = query.from(Appointment.class);
CriteriaQuery<Appointment> selectQuery = query.select(from);
selectQuery = selectQuery.where(completePredicate);
searchResults = entityManager.createQuery(selectQuery).setFirstResult(searchRequest.getIndex()).setMaxResults(searchRequest.getSize()).getResultList();
}catch (Exception e){
//
}
return searchResults;
}
When I run this code, at the following line:
searchResults = entityManager.createQuery(selectQuery).setFirstResult(searchRequest.getIndex()).setMaxResults(searchRequest.getSize()).getResultList();
I am getting the error:
17:20:27,730 ERROR [org.hibernate.hql.internal.ast.ErrorCounter] (http-/127.0.0.1:8080-2) Invalid path: 'generatedAlias1.title'
17:20:27,734 ERROR [org.hibernate.hql.internal.ast.ErrorCounter] (http-/127.0.0.1:8080-2) Invalid path: 'generatedAlias1.title': Invalid path: 'generatedAlias1.title'
at org.hibernate.hql.internal.ast.util.LiteralProcessor.lookupConstant(LiteralProcessor.java:119) [hibernate-core-4.2.7.SP1-redhat-3.jar:4.2.7.SP1-redhat-3]
What could be causing this error?
Ironically i just had exactly the same issue some days ago: the problem is your path "generatedAlias1.title" which is understandable in JPQL as a dereference of the field title from an inner entity referenced with generatedAlias1.
Unluckily this complex path in a single String cannot be understood by the CriteriaBuilder.
This path is normally described within the Predicate element which you are passing here as an argument to your method getSearchResults with name completePredicate ... ( the problem is that you did not tell us how you are creating this predicate )
So you need to refactor the way in which you declare this path, eventually using the class javax.persistence.criteria.Path and calculating it with this method
final private <V> Path<V> getPath(Root<T> root, String attributeName) {
Path<V> path = null;
for (String part : attributeName.split("\\.")) {
path = (path == null) ? root.get(part) : path.get(part);
}
return path;
}
Where you will pass the property from of your method getSearchResults as the argument root, and the string containing "generatedAlias1.title" as attributeName; then you can re-declare your predicate as an instance of Predicate which is acting on this path here returned.
I hope I have been clear enough