假設我有一個Foo物體(欄位:id和name)barId和一個Bar物體(欄位:id,age),處于一對多關系中。我想選擇所有s,并附上Foo相應的 Bar 。age
我看到 2 個選項,但似乎沒有一個有效:
- 所謂封閉投影法
@Query("select f as foo, b.age as age from Foo f inner join Bar b on f.barId = b.id")
List<FooWithAge> query1();
其中 FooWithAge 是一個具有 as 方法和的介面;Foo getFoo()Integer getAge()
- 所謂的類投影方法
@Query("select new FooWithAge(new Foo(f), b.age) from Foo f inner join Bar b on f.barId = b.id")
List<FooWithAge> query2();
其中 FooWithAge 是一個具有 as 欄位的類Foo foo和Integer age一個將這兩個作為引數的建構式。
這些解決方案似乎都不起作用。第三種解決方案是將 Foo 的所有欄位作為 FooWithAge 的建構式的引數,但我想找到一個更清潔的解決方案。
注意:除了普通的 Spring Data JPA 查詢,我不能使用其他任何東西。本機查詢被排除在外。
uj5u.com熱心網友回復:
- 對于 foo 物件,您必須定義一個子介面:
public interface FooWithAge {
String getAge();
FooView getFoo();
interface FooView {
//list of getters of foo
}
}
- 在第一個引數中,您在 foo 中創建 foo,所以基本上您只需傳遞
f:
@Query("select new FooWithAge(f, b.age) from Foo f inner join Bar b on f.barId = b.id")
List<FooWithAge> query2();
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/505385.html
上一篇:具有不同表的hql請求
下一篇:SpringJPA/HIbernate-堅持到H2作業正常,但Oracle失敗,ORA-01400“無法插入NULL”
