java - 有没有办法在没有投影的情况下在spring数据rest中返回带有id的关联对象

标签 java spring spring-data-rest

我正在使用 spring-boot-starter-parent 1.4.1.RELEASE。

  1. Spring boot @ResponseBody 默认不序列化实体 ID。

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

例如

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

是否有更简单的配置来做到这一点而无需配置每个实体类。

引用:https://jira.spring.io/browse/DATAREST-366

  1. REST 资源会将属性呈现为其对应关联资源的 URI。我们需要返回关联对象而不是 URI。

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

例如

@Entity
public class Person {

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

  @ManyToOne
  private Address address;
  …
}

个人资料库:

interface PersonRepository extends CrudRepository<Person, Long> {}

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"
    }
  }
}

如果其他一些类将关联作为地址,那么我也需要为这些类添加投影。

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

引用:https://jira.spring.io/browse/DATAREST-221

最佳答案

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

关于java - 有没有办法在没有投影的情况下在spring数据rest中返回带有id的关联对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123404/

相关文章:

java - 对象序列化问题

java - 从 JList 中删除项目

java - 有条件地将数据发送到 Spring Batch 中的多个写入器

使用 Spring 的 Java EE 项目

javascript - 将 Extjs 与 HAL 集成

java - Java使用的内存多于堆大小(或正确大小的Docker内存限制)

java - Hibernate 无法打开连接

java - 如何使用 Spring Data REST 存储库创建和连接相关资源?

json - @RestResource(exported=false) 被忽略

java - 替换字符串末尾的感叹号