4

因此,我正在尝试基于以下类(稍微简化一点)编写一个 JPA 查询,该查询将产生以下结果:

所以我有两个对象:Thing 和 Person。一个人可以持有对单个事物的引用。以下是类的简化版本:

public class Thing {
    @Id
    public Long id;
    public String name;
    public String description;
}

public class Person {
    @Id
    public Long id;
    public String firstname;
    public String lastname;
    @ManyToOne
    public Thing thing;
}

我正在尝试编写一个 JPA 查询,它将为我提供每个 Thing 对象的所有详细信息以及 Person 对象引用 Thing 对象的次数。请注意,Person 的 Thing 值可能为 null。此外,Thing 对象可能根本不会被任何 Person 对象引用,但仍应列出。

所以给定下表:

Thing Table
| id | name | description |
|  1 | thg1 | a thing     |
|  2 | thg2 | another one |
|  3 | thg3 | one more    |

Person Table
| id | firstname | lastname | thing |
|  1 | John      | Smith    |     1 |
|  2 | Simon     | Doe      |     3 |
|  3 | Anne      | Simmons  |     1 |
|  4 | Jessie    | Smith    |     1 |
|  5 | Adam      | Doe      |     3 |
|  6 | Phil      | Murray   |  null |

我最终会得到如下结果:

| id | name | description | amount |
|  1 | thg1 | a thing     |      3 |
|  2 | thg2 | another one |      2 |
|  3 | thg3 | one more    |      0 |

我将如何编写该 JPA 查询?(如果有什么不同,我使用的是 Play Framework 1.2.5)

4

2 回答 2

4

它应该是这样的:

select t.id, t.name, t.description, count(p) as amount
         from Person as p right join p.thing as t group by t.id

不寻常的“右连接”的原因是 JPA 查询需要查询类之间的映射,而您只有一个 from Personto Thing

如果您有从Thingto的映射Person

class Thing {
    ...
    @OneToMany
    Set<Person> persons;
}

您可以使用经典的“左连接”:

select t.id, t.name, t.description, count(p) as amount
             from Thing as t left join t.persons as p group by t.id
于 2013-04-02T16:06:30.390 回答
0

好的,如果我正在编写纯 JPQL 并设置实体关系,那么我会这样:

public class Thing {
    @Id
    public Long id;
    public String name;
    public String description;
    @OneToMany
    public Collection<Person> personList;

}

public class Person {
    @Id
    public Long id;
    public String firstname;
    public String lastname;
}

询问:

SELECT t from Thing {WHERE watever condition you may have}

迭代:

Collection<Thing> thingList = query.getResultList();

System.out.println("| id | name | description | amount |");
for(Thing thing:thingList){
System.out.format("|  %s | %s | %s    |      %s |%n", thing.getId(), thing.getName(), thing.getDescription(), thing.getPersonList().size());
}
于 2013-04-02T16:08:42.313 回答