Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join two un-related tables using JPA EntityManager

Tags:

java

jpa

jpa-2.0

I need to join two JPA entities on a property when there is no FK/PK relation between the two. I am using Hibernate and can use HQL query like this

 select foo, bar from FooEntity as foo, BarEntity as bar
 where  foo.someothercol = 'foo' and foo.somecol = bar.somecol

However, I want to avoid dependency on Hibernate and use EntityManager instead. Please help.

like image 656
ajay Avatar asked Mar 28 '12 16:03

ajay


People also ask

How do you join unrelated entities in Hibernate?

Hibernate 5.1 Instead of referencing the attribute which defines the relationship between the two entities, you have to reference the second entity which you want to join and define the join criteria in the ON part of the statement. em. getTransaction(). commit();

Can a JPA entity have multiple OneToMany associations?

You can have multiple one-to-many associations, as long as only one is EAGER. But, even if you can use Set instead of List to bypass this MultipleBagFetchException , it's not a good thing to do because you'll end up with a Cartesian Product.


1 Answers

Your query is valid JPQL and does not use Hibernate specific functionality (just space between bar and from is missing). In JPA 2.0 specification (4.4.5 Joins) this is explained with following words:

An inner join may be implicitly specified by the use of a cartesian product in the FROM clause and a join condition in the WHERE clause. In the absence of a join condition, this reduces to the cartesian product.

The main use case for this generalized style of join is when a join condition does not involve a foreign key relationship that is mapped to an entity relationship. Example: SELECT c FROM Customer c, Employee e WHERE c.hatsize = e.shoesize

Main difference to your query is that your select contains two types of entities. Result of query is List of Object[]. Order of elements in array is same as in select statement. Following works in your case:

String query =
    "select foo, bar from  FooEntity as foo, BarEntity as bar "+
    "where  foo.someothercol = 'foo' and foo.somecol = bar.somecol";
List<Object[]> results = em.createQuery(query).getResultList();

for (Object[] fooAndBar: results) {
    FooEntity foo = (FooEntity) fooAndBar[0];
    BarEntity bar = (BarEntity) fooAndBar[1];
    //do something with foo and bar
}
like image 129
Mikko Maunu Avatar answered Oct 25 '22 08:10

Mikko Maunu