5

I have a Person Repository as follows

@RepositoryRestResource
public interface PersonRepository extends Repository<Person, String> {
    List<Person> findAll();

    default List<Person> findNewPersons() {
         return findByStartDateAfter(LocalDate.now().minusMonths(3));
    }
    List<Person> findByStartDateAfter(LocalDate date);
}

I am not able to expose the default method through rest.. is there a way to do it without creating an implementation of the repo ?

  • findByStartDateAfter should be reachable via the search resource: http://docs.spring.io/spring-data/rest/docs/current/reference/html/#repository-resources.search-resource – benkuly Apr 19 '17 at 09:41
  • 3
    I am able to reach `findByStartDateAfter` , I am looking to access the `findNewPersons` (the default method) – rathinakumar Apr 20 '17 at 21:51
  • 1
    @rathinakumar, did you find solution? – Ivan M. Nov 09 '17 at 14:12

3 Answers3

2

I faced a similar problem, and was able to solve it using a SpEL expression inside an HQL query in a @Query annotation.

While nowhere near as clean as using a default method, this was the tidiest way I could find without writing a custom controller or introducing a custom implementation with a new DSL library or something for just this one query.

@Query("select p from Person p where p.startDate > :#{#T(java.time.LocalDate).now().minusMonths(3)}")
List<Person> findNewPersons();

My actual query was different so I might have typoed the syntax here, but the idea is the same and it worked for my case (I was using a LocalDate parameter and finding timestamps on that day by using a findByTimestampBetween style query).

Player One
  • 607
  • 6
  • 12
0

First of all in the specific case best solution is to write query method.

To expose method to REST via @RepositoryRestResource need to create your own inteface which your class annotated with @RepositoryRestResource extends and then write Impementation for that interface.

@RepositoryRestResource
public interface PersonRepository extends Repository<Person, String>, 
MyNewPersonRepository { ... } 

public interface MyNewPersonRepository { 
   Optional<Person> getNewPerson(); 
}

public MyNewPersonRepositoryImpl implements MyNewPersonRepository {
   @Override 
   Optional<Person> getNewPerson() {
      return ...; 
   }
}
user3852017
  • 190
  • 1
  • 9
0
@Configuration
public class AppRepositoryConfig implements RepositoryRestConfigurer {

    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {

        config.setExposeRepositoryMethodsByDefault(true);
    }
}
Mirlo
  • 625
  • 9
  • 26