Search code examples
javaspring-bootspring-hateoas

How to use Java Generics for creating HAL links for entities


I am using Springboot v 2.3.2.

I have different entity class say A and B. Now after performing the CRUD operations I need to return responses in HAL format. Currently I have created methods in each controller classes. But overtime I can see that these are similar in nature. Hence I am thinking of refactoring it and applying Java Generics.

Here is a code snippet. Please guide how can I make this change or there is some other better way.

In both these methods apart from type of entity everything is same.

    import org.springframework.hateoas.EntityModel;
    private final RepositoryEntityLinks entityLinks;

    private EntityModel<A> generateLinks(A a) {
        EntityModel<A> resource = EntityModel.of(a);
        resource.add(entityLinks.linkToItemResource(A.class, a.getId()).withSelfRel());
        resource.add(entityLinks.linkToCollectionResource(A.class));
        resource.add(entityLinks.linksToSearchResources(A.class));
        return resource;
    }

    private EntityModel<B> generateLinks(B b) {
        EntityModel<B> resource = EntityModel.of(b);
        resource.add(entityLinks.linkToItemResource(B.class, b.getId()).withSelfRel());
        resource.add(entityLinks.linkToCollectionResource(B.class));
        resource.add(entityLinks.linksToSearchResources(B.class));
        return resource;
    }

Solution

  • Here is a way to achieve this.

        public  <T> EntityModel<T> generateLinks(T entity, Object id) {
            EntityModel<T> resource = EntityModel.of(entity);
            resource.add(entityLinks.linkToItemResource(entity.getClass(), id).withSelfRel());
            resource.add(entityLinks.linkToCollectionResource(entity.getClass()));
            resource.add(entityLinks.linksToSearchResources(entity.getClass()));
            return resource;
        }