简体   繁体   English

Spring 数据 JPA 查询 - class 投影包含另一个自定义 ZA8CFDE6331BD59EB2AC96F8911C4B666

[英]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实体(字段: idnamebarId )和一个Bar实体(字段: idage ),是一对多的关系。 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 个选项,但似乎没有一个有效:

  1. The so-called closed projection approach所谓封闭投影法
@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()接口

  1. The so-called class projection approach所谓class投影方式
@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 fooInteger 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.本机查询被排除在外。

  1. For foo object you have to define a sub-interface:对于 foo object 你必须定义一个子接口:
public interface FooWithAge {
 
    String getAge();
    FooView getFoo();
     
    interface FooView {
        //list of getters of foo
    }
}
  1. In the first parameter you are creating a foo in a foo, so basically you have just to pass f :在第一个参数中,您在 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM