java 使用一个 JPQL 查询连接多个表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44144693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Join multiple tables with one JPQL query
提问by acroscene
I got this sql-query I want to create as query in JPQL but I cannot get it right. I got a manytoone relationship between QuestionAnswers and QuizQuestions:
我得到了这个 sql 查询,我想在 JPQL 中创建为查询,但我做对了。我在 QuestionAnswers 和 QuizQuestions 之间有一个多对一的关系:
SQL:
查询语句:
SELECT quizName, question, answer FROM Quiz
JOIN QuizQuestions on Quiz.quizId = QuizQuestions.Quiz_QuizId
JOIN QuestionAnswers on QuizQuestions.questionId = QuestionAnswers.question_questionId
WHERE quiz.quizId = 1;
JPQL query:
JPQL 查询:
Query query = entityManager.createQuery("SELECT q.quizName, f.question, a.answer FROM Quiz q, QuizQuestions f, QuestionAnswers a LEFT JOIN QuestionAnswers ON f.questionId=a.question.questionId");
I get syntax error in Intellij.
我在 Intellij 中遇到语法错误。
What can be wrong?
有什么问题?
Im using EclipseLink
我正在使用 EclipseLink
EDITsolved it like this with just one join:
EDIT只用一个连接就解决了这个问题:
Query query = entityManager.createQuery("SELECT f.quiz.quizName FROM QuizQuestions f JOIN QuestionAnswers qa WHERE f.questionId = qa.question.questionId");
回答by Dherik
Probably, you are looking for a JPQL like this:
可能您正在寻找这样的 JPQL:
SELECT quiz.name, quizquestion.question, questionasnswer.answer FROM Quiz quiz
JOIN quiz.quizQuestions quizquestion
JOIN quizquestion.questionAnswers questionasnswer
WHERE quiz.id = 1;
I would evict solutions with qa.question.questionId
(tableA.tableB.column), because the JPA framework not always generate nice SQLs from this. Always explicit the JOINs in the JPQL.
我会用qa.question.questionId
(tableA.tableB.column)驱逐解决方案,因为 JPA 框架并不总是从中生成好的 SQL。始终在 JPQL 中显式显示 JOIN。