Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining tables without relation using JPA criteria

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?

like image 665
Idan Avatar asked Jun 04 '15 08:06

Idan


People also ask

How to join two unrelated entities in JPA?

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.

How do I join two tables in JPA?

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:

Does JPA support join on clause in JPQL?

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.

What is the use of Relationship Attribute in JPQL?

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.


1 Answers

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.

like image 68
Neil Stockton Avatar answered Oct 13 '22 19:10

Neil Stockton