从Spring 5开始,我们可以选择使用多个片段存储库丰富JPA存储库。
这个机制非常简单:声明然后实现一个接口。
public interface CustomRepository<T,K> {
// my very special finder
T findByIdCustom(K id);
}public class CustomRepositoryImpl implements CustomRepository<T,K> {
T findByIdCustom(K id) {
// retrieve the item
}
}然后,像这样使用它:
public interface ItemRepository
extends JpaRepository<Item, Long>, CustomRepository<Item, Long> {
}现在,假设我想设置一些查询提示和/或如下所示的实体图:
public interface ItemRepository extends JpaRepository<Item, Long>, CustomRepository<Item, Long>{
@QueryHints(value = { @QueryHint(name = "name", value = "value")},
forCounting = false)
@EntityGraph(value = "Item.characteristics")
Item findByIdCustom(Long id);
}由于我有一个自定义实现,所以这里忽略了上面的查询提示和实体图,它们在JpaRepository方法上很好地工作。
我的问题是:
如何将方法的元数据应用于底层查询?
发布于 2019-06-03 14:06:51
您所要求的不能使用注释,因为它们用于存储库方法,Spring为其提供了实现。对于自定义方法,Spring通常忽略它--因为您的自定义代码负责构建、配置和执行查询,因此Spring无法神奇地在中间进行干预并注入查询提示。本质上,如果您需要定制查询方法的两组不同的提示,则需要两种不同的实现。
然而,您可能尝试的是一种类似于这样的模板方法模式:
public interface CustomRepository<T,K> {
T findByIdCustom(K id);
Map<String, Object> getHintsForFindByIdCustom();
// you'll probably need a default implementation for getHintsForFindByIdCustom here, unless it's possible to make CustomRepositoryImpl abstract - not sure how Spring Data will behave in this case
}
public class CustomRepositoryImpl<T, K> implements CustomRepository<T,K> {
T findByIdCustom(K id) {
TypedQuery<T> query= em.createQuery("...");
getHintsForFindByIdCustom().forEach((key, value) -> query.setHint(key, value));
return query.getResultList().iterator().next();
}
}
public interface ItemRepository extends JpaRepository<Item, Long>, CustomRepository<Item, Long>{
default Map<String, Object> getHintsForFindByIdCustom() {
return Map.of("name", "value");
}
}
public interface UserRepository extends JpaRepository<User, Long>, CustomRepository<User, Long>{
default Map<String, Object> getHintsForFindByIdCustom() {
return Map.of("name", "some-other-value");
}
}请注意,我没有尝试上述代码。如果它不起作用,那么也许您可以为每个实体类尝试一个单独的CustomRepositoryImpl实现。
https://stackoverflow.com/questions/56231784
复制相似问题