[英]Spring Data JPA Query - class projection containing another custom object
Suppose I have a Foo
entity (fields: id
, name
and barId
) and a Bar
entity (fields: id
, age
), in a one-to-many relation.假设我有一个
Foo
实体(字段: id
、 name
和barId
)和一个Bar
实体(字段: id
、 age
),是一对多的关系。 I want to select all the Foo
s, having the corresponding Bar age
attached.我想 select 所有
Foo
,附有相应的 Bar age
。
I see 2 options, but none seems to work:我看到 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();
where FooWithAge is an interface having as methods Foo getFoo()
and Integer getAge()
;其中 FooWithAge 是具有方法
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();
where FooWithAge is a class having as fields Foo foo
and Integer age
and a constructor that takes these 2 as parameters.其中 FooWithAge 是一个class具有字段
Foo foo
和Integer age
和一个将这 2 个作为参数的构造函数。
None of these solutions seem to work.这些解决方案似乎都不起作用。 A third solution, of taking all the fields of Foo as parameters of the constructor of FooWithAge works, but I would like to find a cleaner solution.
第三种解决方案是将 Foo 的所有字段作为 FooWithAge 的构造函数的参数,但我想找到一个更清洁的解决方案。
Note: I cannot use anything else than vanilla Spring Data JPA queries.注意:除了普通的 Spring 数据 JPA 查询,我不能使用其他任何东西。 Native queries are excluded.
本机查询被排除在外。
public interface FooWithAge {
String getAge();
FooView getFoo();
interface FooView {
//list of getters of foo
}
}
f
:f
:@Query("select new FooWithAge(f, b.age) from Foo f inner join Bar b on f.barId = b.id")
List<FooWithAge> query2();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.