编程语言
首页 > 编程语言> > java – 使用JPQL从两个表中选择

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

作者:互联网

我正在使用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));
}

现在我想获取专辑名称和roleuser的名为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)并获取firstname和albumname?

解决方法:

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

SELECT子句中具有多个select_expressions的查询返回Object [](或Object []列表).从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,orm,jpa-2-0,jpql,openjpa
来源: https://codeday.me/bug/20190526/1158205.html