我有一个人员存储库,如下
@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);
}
我无法通过休息公开默认方法。有没有办法在不创建存储库的实现的情况下做到这一点?
我遇到了类似的问题,并且能够在
@Query
注释中的 HQL 查询中使用 SpEL 表达式来解决它。
虽然远不如使用默认方法那么干净,但这是我能找到的最简洁的方法,无需编写自定义控制器或使用新的 DSL 库引入自定义实现或仅针对此一个查询。
@Query("select p from Person p where p.startDate > :#{#T(java.time.LocalDate).now().minusMonths(3)}")
List<Person> findNewPersons();
我的实际查询不同,所以我可能在这里拼写了语法,但想法是相同的,并且它适用于我的情况(我使用
LocalDate
参数并通过使用 findByTimestampBetween
样式查询查找当天的时间戳).
首先针对具体情况最好的解决方案是编写查询方法。
要通过 @RepositoryRestResource 向 REST 公开方法,需要创建您自己的接口,您的类用 @RepositoryRestResource 注释扩展该接口,然后为该接口编写 Impementation。
@RepositoryRestResource
public interface PersonRepository extends Repository<Person, String>,
MyNewPersonRepository { ... }
public interface MyNewPersonRepository {
Optional<Person> getNewPerson();
}
public MyNewPersonRepositoryImpl implements MyNewPersonRepository {
@Override
Optional<Person> getNewPerson() {
return ...;
}
}
@Configuration
public class AppRepositoryConfig implements RepositoryRestConfigurer {
@Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.setExposeRepositoryMethodsByDefault(true);
}
}