【问题标题】:Spring how to keep entity id of all sub entities within the json generated by @Controller?Spring如何在@Controller生成的json中保留所有子实体的实体ID?
【发布时间】:2020-06-22 00:53:09
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

您可以使用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);
    }
}

【讨论】:

  • 我有:Field entityManager in com.myapp.api.config.context.security.RepositoryRestConfig required a bean of type 'javax.persistence.EntityManager' that could not be found.
  • 您是否使用关系数据库和 Spring Data JPA 或其他不同的东西来进行存储?
  • 我尝试在 MyRepositoryRestConfigurerAdapter 中添加一个 @ConditionalOnBean(EntityManager.class) ,但是没有调用该方法,并且 id 仍然没有暴露。我将 Spring 数据与 spring data mybatis 一起使用:github.com/hatunet/spring-data-mybatis
  • 啊,好吧,这很重要,因为 MyBatis 不使用 JPA,因此您不会准备好注入 EntityManager,这是 JPA 规范的一部分并由 Hibernate 实现
  • 我已经添加了另一个解决方案,你可以试试这个吗?
猜你喜欢
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-27
  • 2022-01-05
相关资源
最近更新 更多