gpt4 book ai didi

java - 使用 JPQL 从两个表中选择

转载 作者:搜寻专家 更新时间:2023-10-31 19:42:03 25 4
gpt4 key购买 nike

我正在使用 JPQL 来检索数据。我可以使用语句获取数据

List persons = null;
persons = em.createQuery("select p.albumName from PhotoAlbum p , Roleuser r
where r = p.userId and r.userID = 1");

现在我可以使用这个获取相册名称:

int i=0;
for (i=0;i<persons.size(); i++)
{
System.out.println("Testing n "+ i +" " + persons.get(0));
}

现在我想获取相册名称和名为 firstname 的角色用户的行

我正在使用查询

persons = em.createQuery("select r.firstName , p.albumName from PhotoAlbum p ,   
Roleuser r where r = p.userId and r.userID = 1").getResultList();

现在我如何获取 firstname 和 albumname 行,因为 persons.get(0) 正在返回一个对象

通过运行代码:

 for (i=0;i<persons.size(); i++)
{
//r = (Roleuser) persons.get(i);
System.out.println("Testing n "+ i +" " + persons.get(i));
}

我明白了:

Testing n 0 [Ljava.lang.Object;@4edb4077
INFO: Testing n 1 [Ljava.lang.Object;@1c656d13
INFO: Testing n 2 [Ljava.lang.Object;@46dc08f5
INFO: Testing n 3 [Ljava.lang.Object;@654c0a43

如何映射 persons.get(0) 并获取 firstnamealbumname

最佳答案

Now how do get the rows firstname and albumname as the persons.get(0) is returning a object

在 SELECT 子句中包含多个select_expressions 的查询返回 Object[] (或 ListObject[] )。来自 JPA 规范:

4.8.1 Result Type of the SELECT Clause

The type of the query result specified by the SELECT clause of a query is an entity abstract schema type, a state-field type, the result of an aggregate function, the result of a construction operation, or some sequence of these.

The result type of the SELECT clause is defined by the the result types of the select_expressions contained in it. When multiple select_expressions are used in the SELECT clause, the result of the query is of type Object[], and the elements in this result correspond in order to the order of their specification in the SELECT clause and in type to the result types of each of the select_expressions.

所以在你的情况下,你可能想要这样的东西:

for (i=0;i<persons.size(); i++) {
//r = (Roleuser) persons.get(i);
System.out.println("Testing n " + i + " " + persons.get(i)[0] + ", " +
persons.get(i)[1]);
}

请注意,通过在 FROM 子句中使用笛卡尔积和在 WHERE 子句中使用连接条件来指定内部连接不如在实体关系上指定显式连接(使用 [LEFT [OUTER] | INNER ] JOIN 语法)典型。请参阅规范中的整个 4.4.5 连接部分。

引用资料

  • JPA 1.0 规范
    • 第 4.8.1 节“SELECT 子句的结果类型”
    • 第 4.8.2 节“SELECT 子句中的构造函数表达式”
    • 第 4.4.5 节“加入”

关于java - 使用 JPQL 从两个表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3567438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com