4

だから私は、以下を生成する以下のクラスに基づいてJPAクエリを作成しようとしています(少し馬鹿げています):

つまり、Thing と Person という 2 つのオブジェクトがあります。Person は、単一の Thing への参照を保持できます。クラスの簡略化されたバージョンは次のとおりです。

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;
}

すべての Thing オブジェクトのすべての詳細と、その Thing オブジェクトが Person オブジェクトによって参照される回数を取得する JPA クエリを作成しようとしています。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 から まで 1 つしかないPersonためThingです。

Thingからへのマッピングがある場合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 に答える