Search code examples
jpaeclipselinkjpqlcriteria-api

CriteriaBuilder and using alias for select cause


I would like to create a query with CriteriaBuilder for this kind of sql;

SELECT myDefinedAlias.id, myDefinedAlias.name, myDefinedAlias.aFieldForFK select from Person as myDefinedAlias where myDefinedAlias.name = ?1

How can i accomplish defining an alias for this?

I can create queries without aliases but i cannot define aliases...

CriteriaQuery<Person> cq = criteriBuilder.createQuery(Person.class);
Root<Person> person = cq.from(Person.class);
cq = cq.select(person);
cq = cq.where(criteriaBuilder.equal(person.get(Person_.name), "Chivas")))

I need this for QueryHints, batch fetch.

.setHint(QueryHints.BATCH, "myDefinedAlias.aFieldForFK.itsNestedAttribute"); 

I am stuck and couldn't find anything regarding my problem. Anyone?

Regards


Solution

  • I think you are going about this the wrong way. JPA needs the sql-statement-aliases for itself to use when generating sql-statements. For the nested query hints to work, the relationship needs to be specified in the entities. For example, if your Person entity have a OneToMany mapping to a House entity - and the property name in the Person class is livedInHouses. The query hint would become: .setHint(QueryHints.BATCH, "Person.livedInHouses"). Its damn near impossible to use FKs that exists in the database but are not annotated as relations on/in entities in JPA.