Video in progress
Can you join two entities in JPQL/HQL that have no association in the mapping?
Yes. Since Hibernate 5.1 there is the "entity join": join Payment p on p.orderNumber = o.number, and there doesn't have to be a @ManyToOne or @OneToMany. It lets you write report and verification queries without cluttering the mapping with extra associations.
📖 Answer
The situation: the Payment table comes from an external system and is linked to the order only through the order_number string. There is no mapping between the entities, and adding one isn't required.
List<Object[]> rows = em.createQuery("""
select o.number, o.total, p.amount
from Order o
left join Payment p on p.orderNumber = o.number
where o.createdAt >= :from""", Object[].class)
.setParameter("from", from)
.getResultList();
left join works, and you can put any condition in the on. You can also take the result straight into a DTO:
select new com.shop.report.PaymentCheck(o.number, o.total, p.amount)
from Order o left join Payment p on p.orderNumber = o.number
The old way is from Order o, Payment p where ... (a theta-style join). It gives only an inner join and reads worse.
What I watch for:
- such joins aren't fetched: the result is scalars or a DTO, and no entity collection gets filled;
- you need an index on the columns in the
on, otherwise a hash join or a full scan on a big table; - if the same join repeats in many places, it's a real domain association, and adding a mapping may be the better choice.
In Spring Data you write the same thing inside @Query. JPA 3.2 also brought this kind of join into the standard.
Sign up to mark studied questions and save your progress.