简体   繁体   English

如何在JPA2标准查询中使用多个联接?

[英]How can I use multiple Joins in JPA2 Criteria Query?

It's a dum down version of a real problem 这是一个真正问题的精简版

I have Three Tables STUDENT ADDRESS CLASS 我有三张桌子的STUDENT ADDRESS CLASS

STUDENT ManyToOne ADDRESS STUDENT ManyToMany CLASS STUDENT ManyToOne ADDRESS STUDENT ManyToMany CLASS STUDENT ManyToOne ADDRESS

I need to bring all the students who have same address and go to same class. 我需要带所有有相同地址的学生去同一堂课。

Sql would simply be (just writing this on the fly and have not tested it) sql可能就是(只是即时编写此代码,而尚未对其进行测试)

Select * from STUDENT s join ADDRESS a on s.addressId = a.addressId join CLASS c on c.classId = s.classId

Now I am new to Criteria and while have been able use it reasonbly so far , I am totally stuck as how should I do this join have looked every where documentation by Oracle , Jboss etc but no indication on how this should be done and all the stabs I have taken in the dark have been unsuccessful. 现在我是Criteria的新手,到目前为止,虽然可以合理地使用它,但我完全陷入了困境,因为我应该如何进行此连接,查看了Oracle,Jboss等文档的每一个地方,但没有说明应如何做以及所有这些。我在黑暗中拍摄的刺刺未成功。 Even on SO there are many questions in similar tone but when you read them it is something else thats being ask. 即使在SO上,也有许多类似音调的问题,但是当您阅读它们时,那​​是在问其他问题。

Assuming that your Student class defines a collection that is managed by JPA, you shouldn't need to define any joins in your JPQL query. 假设您的Student类定义了由JPA管理的集合,则您无需在JPQL查询中定义任何联接。 Just retrieve the Student object and OpenJPA will retrieve the addresses and classes automatically. 只需检索Student对象,OpenJPA就会自动检索地址和类。

You can try this: 您可以尝试以下方法:

Root<STUDENT> from = criteriaQuery.from(STUDENT.class);
Join<STUDENT, ADDRESS> joinAddress = from.join(STUDENT_.address);
Join<STUDENT, CLASS> joinClass = from.join(STUDENT_.class);

Before this you should generate the meta classes from your entities. 在此之前,您应该从您的实体生成元类。

javac -classpath "PATHTOLIBRARIES\openjpa-all-2.2.2.jar" -Aopenjpa.metamodel=true STUDENT.java ADDRESS.java CLASS.java

PS: if you don't need to do anything extra with the result of 'from.join' you can just ignore the resurned value. PS:如果您不需要对'from.join'的结果做任何额外的事情,则可以忽略该保留的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM