简体   繁体   中英

Spring how to keep entity id of all sub entities within the json generated by @Controller?

In spring data, I have a Entity that use EntityStatus .

When I serialized json using my @Controller , the id of EntityStatus is removed.

This is how look the generated entity:

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

How can I force it to be included for all sub-entities globally?

You can configure this using the RepositoryRestConfigurerAdapter . If you want to have it for all your entities, just iterate over all of them and expose their ids:

@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]));
    }

}

If you just want it for specific entities, filter them out while doing the processing above.

UPDATE : Another more manual approach without using the EntityManager might be to explicitly add all entities:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM