微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 有没有办法在没有Projection的情况下在spring数据中返回带有id的关联对象

我使用的是spring-boot-starter-parent 1.4.1.RELEASE.

> Spring启动@ResponseBody认情况下不会序列化实体ID.

如果我使用exposeIdsFor返回id,但我需要为每个类配置它

例如

RepositoryRestConfiguration.exposeIdsFor(User.class);
RepositoryRestConfiguration.exposeIdsFor(Address.class);

是否有更简单的配置来执行此操作而不配置每个实体类.

参见:https://jira.spring.io/browse/DATAREST-366

> REST资源将该属性作为URI呈现给它对应的关联资源.我们需要返回关联的对象而不是URI.

如果我使用Projection,它将返回关联的对象,但我需要为每个类配置它

例如

@Entity
public class Person {

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

  @ManyToOne
  private Address address;
  …
}

PersonRepository:

interface PersonRepository extends CrudRepository

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","address" : { 
    "street": "Bag End","state": "The Shire","country": "Middle Earth"
  },"address" : { 
      "href" : "http://localhost:8080/persons/1/address"
    }
  }
}

如果其他一些类具有关联作为地址,那么我还需要为这些类添加投影.

但我不想为每个类配置.如何实现动态投影?这样我的所有实体都将返回嵌套对象作为响应.

参见:https://jira.spring.io/browse/DATAREST-221

最佳答案
关于您的第一个问题,已经回答了here,exposeIdsFor接受了任意数量的参数.另外,如提到in this thread如果所有实体类都位于同一个包中,您可以使用Reflections library获取类的列表并将其提供给exposeIdsFor().

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐