I have two tables with no modeled relation:
Table comm
with columns:
name
date
code
Table persondesc
with columns:
code
description
Relationship between the two tables is many to one (many comm to one persondesc):
com.code = persondesc.code
These two tables are mapped with annotations but I have no relation declared.
What I'm trying to is to select comm
table ordered by persondesc.description
.
How can I do this JPA and Hibernate?
The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.
Joining Tables with JPA Specifications We can observe from our data model that the Author entity shares a one-to-many relationship with the Book entity: The Criteria Query API allows us to join the two tables when creating the Specification. As a result, we'll be able to include the fields from the Book entity inside our queries:
Although JPA 2.0 has introduced support for JOIN ON clause in JPQL queries, this syntax requires the association to be present at the entity level. However, in our case, our entities are unrelated so there is no such association present.
It makes it very easy to navigate from one entity to one or more related entities in your Java code, like from a Person entity to the corresponding Address entity. You can also use the relationship attributes in JPQL queries to join related entities.
So if your classes have no "relation", then you do a query like
SELECT a FROM A a
CROSS JOIN B b
WHERE a.someField = b.otherField
ORDER BY b.anotherField
Which can be achieved using JPA Criteria, something like
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<A> query = cb.createQuery(A.class);
Root<A> aRoot = query.from(A.class);
Root<B> bRoot = query.from(B.class);
aRoot.alias("a");
bRoot.alias("b");
query.select(aRoot)
.where(cb.equal(aRoot.get(A_.someField), bRoot.get(B_.otherField))
.orderBy(cb.asc(bRoot.get(B_.anotherField)));
... Or just redesign your classes and do your developers a favour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With