Entity org.hibernate.jpa.test.metamodel.Customer refers org.hibernate.jpa.test.metamodel.Address via a OneToOne attribute named home. The following test case fails:
package org.hibernate.jpa.test.criteria;
import org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest;
import org.hibernate.jpa.test.metamodel.Address;
import org.hibernate.jpa.test.metamodel.Customer;
import org.junit.Test;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
/**
* Created on 27/09/18.
*
* @author Reda.Housni-Alaoui
*/
public class ProjectionJoinTest extends AbstractMetamodelSpecificTest {
@Test
public void testCriteriaQuery() {
EntityManager em = entityManagerFactory().createEntityManager();
em.getTransaction().begin();
Customer customer = new Customer();
customer.setId("c1");
em.persist(customer);
em.getTransaction().commit();
em.close();
em = entityManagerFactory().createEntityManager();
em.getTransaction().begin();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CustomerProjection> cq = cb.createQuery(CustomerProjection.class);
Root<Customer> customerRoot = cq.from(Customer.class);
cq.multiselect(customerRoot.get("id"), customerRoot.get("home"))
.where(cb.equal(customerRoot.get("id"), customer.getId()));
TypedQuery<CustomerProjection> typedQuery = em.createQuery(cq);
typedQuery.getSingleResult(); em.getTransaction().commit();
em.close();
}
static class CustomerProjection {
private final String id;
private final Address home;
public CustomerProjection(String id, Address home) {
this.id = id;
this.home = home;
}
public String getId() {
return id;
}
public Address getAddress() {
return home;
}
}
}
The generated failing sql query is:
select
customer0_.ID as col_0_0_,
customer0_.FK6_FOR_CUSTOMER_TABLE as col_1_0_
from
CUSTOMER_TABLE customer0_
inner join
ADDRESS address1_
on customer0_.FK6_FOR_CUSTOMER_TABLE=address1_.ID
where
customer0_.ID=?
The test fails because a useless (IMO) inner join is generated while customer references no home address. I tried to fix it myself to provide a patch but I am lost between antlr and the hql AST. If you don't have the time to fix this, please give me some hints to fix it myself ![](cid:jira-generated-image-static-smile-dedb2a4b-1e7a-4438-9177-6743cdc6d28e) |