在 Spring 数据中,我有一个使用 EntityStatus
的 Entity
。
当我使用 @Controller
序列化 json 时,EntityStatus
的 id
被删除。
这是生成的实体的外观:
{
"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/