本文介绍了使用JPA EntityManager加入两个不相关的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当两者之间没有FK / PK关系时,我需要在属性上加入两个JPA实体。
我正在使用Hibernate并且可以使用这样的HQL查询

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

但是,我想避免依赖Hibernate并使用EntityManager。
请帮助。

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

推荐答案

您的查询是有效的JPQL,并且不使用Hibernate特定的功能(只是在bar和来自失踪)。在JPA 2.0规范(4.4.5联接)中,用以下单词解释:

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:

这种通用连接方式的主要用例是
a连接条件不涉及映射到实体的
的外键关系关系。示例:SELECT c FROM Customer c,

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

您的查询的主要区别在于您的选择包含两种类型的实体。查询结果是List of Object []。数组中的元素顺序与select
语句中的相同。以下适用于您的情况:

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 selectstatement. 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
}

这篇关于使用JPA EntityManager加入两个不相关的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 17:26