如何为特定方法配置Projection

时间:2016-10-25 11:52:29

标签: java spring spring-boot spring-data-rest

我使用的是spring-boot-starter-parent 1.4.1.RELEASE。 REST资源将该属性呈现为其对应关联资源的URI。我们需要返回关联的对象而不是URI。

Projection将执行关联的对象而不是URI,但我需要为每个类配置它。

e.g

@Entity
public class Person {

  @Id @GeneratedValue
  private Long id;
  private String firstName, lastName;

  @ManyToOne
  private Address address;
  …
}

PersonRepository:

interface PersonRepository extends CrudRepository<Person, Long> {
    Person findByName(@Param("name") @RequestParam("name") String name);
    Person findById(@Param("id") @RequestParam("id") int id);

}

PersonRepository返回

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : {
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

我的预测:

@Projection(name = "inlineAddress", types = { Person.class }) 
interface InlineAddress {

  String getFirstName();

  String getLastName();

  Address getAddress(); 
}

添加投影后,返回..

{
  "firstName" : "Frodo",
  "lastName" : "Baggins",
  "address" : { 
    "street": "Bag End",
    "state": "The Shire",
    "country": "Middle Earth"
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/persons/1"
    },
    "address" : { 
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

我的Person存储库中有2个调用。但我需要 findById 中的扩展关联对象,而不是 findByName

如何在Projection中配置?

如果我配置如下,它返回两个方法但我只需要findById方法中的关联对象。

@RepositoryRestResource(excerptProjection = Inlineaddress.class)
interface PersonRepository extends CrudRepository<Person, Long> {
    Person findByName(@Param("name") @RequestParam("name") String name);
    Person findById(@Param("id") @RequestParam("id") int id);
}

然后如何为特定方法配置投影 ???

1 个答案:

答案 0 :(得分:0)

Spring Data支持从Hopper Release开始从查询方法返回Projection:

https://spring.io/blog/2016/05/03/what-s-new-in-spring-data-hopper#projections-on-repository-query-methods

因此,应该只是从查询方法返回相关的Projection:

@RepositoryRestResource(excerptProjection = Inlineaddress.class)
interface PersonRepository extends CrudRepository<Person, Long> {
    Person findByName(@Param("name") @RequestParam("name") String name);
    InlineAddress findById(@Param("id") @RequestParam("id") int id);
}