java - Spring如何保留@Controller生成的json中所有子实体的实体id?

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

在 Spring 数据中,我有一个使用 EntityStatusEntity

当我使用 @Controller 序列化 json 时,EntityStatusid 被删除。

这是生成的实体的外观:

{
  "description" : "Some testing",
  "version" : null,
  "createdDate" : "2020-03-10T05:46:25.516Z",
  "createdById" : null,
  "lastModifiedById" : null,
  "title" : "This is a test",
  "content" : "Foo bar fizz buzz",
  "userId" : 2,
  "category" : {
    "description" : "Foobar",
    "version" : null,
    "createdDate" : "2020-03-10T05:18:30.282Z",
    "lastModifiedDate" : "2020-03-10T05:18:41.827Z",
    "createdById" : null,
    "lastModifiedById" : null,
    "deleted" : false
  },
  "status" : {
    "description" : "Created"
  },
  "deleted" : false,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/management/entity/5"
    }
  }
}

如何强制将其包含在全局所有子实体中?

最佳答案

您可以使用RepositoryRestConfigurerAdapter进行配置。如果您想为所有实体拥有它,只需迭代所有实体并公开它们的 id:

@Configuration
public class MyRepositoryRestConfigurerAdapter extends RepositoryRestConfigurerAdapter {

    @Autowired
    private EntityManager entityManager;

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(entityManager.getMetamodel().getEntities()
              .stream().map(EntityType:getJavaType))
              .collect(Collectors.toList())
              .toArray(new Class[0]));
    }

}

如果您只想将其用于特定实体,请在执行上述处理时将其过滤掉。

更新:另一种不使用EntityManager的更手动方法可能是显式添加所有实体:

@Configuration
public class MyRepositoryRestConfigurerAdapter extends RepositoryRestConfigurerAdapter {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(YourEntityOne.class);
        config.exposeIdsFor(YourEntityTwo.class);
    }
}

关于java - Spring如何保留@Controller生成的json中所有子实体的实体id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60612310/

相关文章:

java - 列表<?扩展我的类型>

java - 如何从 Java 中的同一个包导入类?

java - 定义 POSITIVE_INFINITY, NEGATIVE_INFINITY, NaN 常量的目的只针对 float 据类型,不针对整型数据类型

java - 无法在 Spring Boot 项目中使用自定义 jar

java - 获取JDBC连接失败;嵌套异常是 java.sql.SQLException : null

java - 如何使用 Spring 的 PayloadValidatingInterceptor 验证多个 XSD 模式

java - 水平对齐 GWT VerticalPanel

java - 向实体中的实例添加属性

java - 将 Facebook 登录添加到 spring mvc 项目时出现 BeanCreationException

java - 如何将本地非maven项目添加为maven项目的依赖?