Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Repositories for the Same Entity in Spring Data Rest

Is it possible to publish two different repositories for the same JPA entity with Spring Data Rest? I gave the two repositories different paths and rel-names, but only one of the two is available as REST endpoint. The point why I'm having two repositories is, that one of them is an excerpt, showing only the basic fields of an entity.

like image 559
Gregor Avatar asked Mar 20 '16 10:03

Gregor


3 Answers

The terrible part is not only that you can only have 1 spring data rest repository (@RepositoryRestResource) per Entity but also that if you have a regular JPA @Repository (like CrudRepository or PagingAndSorting) it will also interact with the spring data rest one (as the key in the map is the Entity itself). Lost quite a few hours debugging random load of one or the other. I guess that if this is a hard limitation of spring data rest at least an Exception could be thrown if the key of the map is already there when trying to override the value.

like image 79
domgom Avatar answered Oct 19 '22 16:10

domgom


I ended up using the @Subselect to create a second immutable entity and bound that to the second JpaRepsotory and setting it to @RestResource(exported = false), that also encourages a separation of concerns.

Employee Example

@Entity @Table(name = "employee") public class Employee {      @Id     Long id      String name      ...  } 
@RestResource public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {  } 
@Entity @Immutable    @Subselect(value = 'select id, name, salary from employee') public class VEmployeeSummary {      @Id     Long id      ...  } 
@RestResource(exported = false) public interface VEmployeeRepository extends JpaRepository<VEmployeeSummary, Long> {  } 

Context

Two packages in the monolithic application had different requirements. One needed to expose the entities for the UI in a PagingAndSortingRepository including CRUD functions. The other was for an aggregating backend report component without paging but with sorting.

I know I could have filtered the results from the PagingAndSorting Repository after requesting Pageable.unpaged() but I just wanted a Basic JPA repository which returned List for some filters.

like image 32
Jonathan Turnock Avatar answered Oct 19 '22 14:10

Jonathan Turnock


The answer seems to be: There is only one repository possible per entity.

like image 33
Gregor Avatar answered Oct 19 '22 14:10

Gregor