Search code examples
springspring-data-rest

Spring Data Rest multiple repositories reusing entities


I am new to Spring Data Rest and am having a play round to expose a many to many relationship as rest based web services. The many to many is content and categories. I would like to have two repositories which allows the data to be displayed in both directions (e.g. list all content items and associated categories and categories with content). I tried to do this with each of the repositories using it's own set of entities but intermittently one of the repositories returns an error saying the repository does not exist.

Is this possible using Spring Data Rest?


Solution

  • Ofcause it possible )) For example:

    Entities:

    @Entity
    public class Content {
        //...
        @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
        private final Set<Category> categories = new HashSet<>();
        //...
    }
    
    @Entity
    public class Category {
        //...
         @ManyToMany(mappedBy = "categories")
         private final Set<Content> contents = new HashSet<>();
        //...
    }
    

    Repositories:

    @RepositoryRestResource(collectionResourceRel = "contents", path = "contents")
    public interface Content extends JpaRepository<Content, Long> {
    }
    
    @RepositoryRestResource
    public interface Category extends JpaRepository<Category, Long> {
    }
    

    See my example and tests.