JPA通过查询联接表 [英] JPA join tables through query
问题描述
我有一个奇怪的问题.我想这样创建数据库: 一个学生可以有很多科目.学生对一门学科有一项评估.所以我有 具有ID,姓名,姓氏和A_I ID的班级学生,例如:
I have strange problem. I want to create database like this: One student can has a lot of subjects. Student has one evaluation for one subject. So I have class student with ID, Name, Surname and A_I id, like:
@Id
@GeneratedValue
long id_student;
在学科课上,我有:
@Id
@GeneratedValue
long id_subject;
String name;
double graduate
我有第三堂课,名为StudentWithGraduate:
I have third class, named StudentWithGraduate:
@Id
@GeneratedValue
long id;
double evaluation;
@OneToOne
Student student;
@OneToOne
Subject subject;
我认为我可以做得更好,但是我不知道如何做.但这不是主要问题.这样,我写的就可以了,但是我想在查询中做一些连接,例如:
I think I could do it better, but I don't know how. But it isn't a main problem. This, what I write up is working, but I want to do some joins in query like:
Vector<Object[]> v = (Vector<Object[]>) em.createQuery(
"select p.name, o.graduate from Student s
left join StudentWithGraduate o on s.id_student=o.student
left join Subject p on p.id_subject=o.subject where
s.surname='"+name+"'").getResultList();
它抛出一个错误: 异常描述:对象比较只能与OneToOneMappings一起使用.其他映射比较必须通过查询键或直接属性级别比较来完成.
And it throw an error: Exception Description: Object comparisons can only be used with OneToOneMappings. Other mapping comparisons must be done through query keys or direct attribute level comparisons.
如何更改此数据库方案或更改该查询?
How can I change this DB scheme or change that query?
对不起,我的英语.
PS.当我进行研究时,我发现了@joinTables,但是我不知道如何使用它.
PS. When I was doing research I found @joinTables, but I don't know how to use it..
推荐答案
You need a short introduction in JPQL, but I will try to quickly explain some missing parts:
在JPQL查询中,您不不写JOIN
条件(即ON
表达式),而是从实体图开始浏览实体图(在下面以StudentWithGraduate
实体开头):
In a JPQL query you do not write which are the JOIN
conditions (i.e the ON
expresions), and instead you navigate through your Entity Graph, beginning with an entity (below I begin with the StudentWithGraduate
entity):
SELECT p.name, o.graduate FROM StudentWithGraduate o
LEFT JOIN o.student s
LEFT JOIN o.subject p
WHERE s.surname=:name
:name"被称为命名参数,它可以帮助您 SQL注入.为了为其设置一个值,您可以编写以下内容:
The ":name" is called a named parameter, which helps you agains SQL injections. In order to set a value for it, you write the following:
Query query = em.createQuery(aboveQuery);
query.setParameter("name", parameterValue);
//....the rest of parameters + getResultList();
这篇关于JPA通过查询联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!