[英]Dynamic JPA querys
我在 JPA/Hibernate 和 spring 引導中相當新,我想根據收到的參數進行動態查詢。 我遵循這種方法https://www.baeldung.com/spring-data-jpa-query ,但是當它說:“另外,我們需要確保在 class 名稱中包含 Impl 后綴。 Spring 將作為 UserRepositoryCustomImpl 搜索 UserRepositoryCustom 實現。由於片段本身不是存儲庫,因此 Spring 依靠這種機制來查找片段實現。
這是什么意思? 如何在 class 名稱中包含 Impl 后綴?
謝謝
這意味着如果您需要在存儲庫中使用任何自定義方法,您需要聲明一個接口,如下所示
public interface UserRepositoryCustom {
List<User> findUserByEmails(Set<String> emails);
}
現在您需要提供接口的實現,如下所示
public class UserRepositoryCustomImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<User> findUserByEmails(Set<String> emails) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> query = cb.createQuery(User.class);
Root<User> user = query.from(User.class);
Path<String> emailPath = user.get("email");
List<Predicate> predicates = new ArrayList<>();
for (String email : emails) {
predicates.add(cb.like(emailPath, email));
}
query.select(user)
.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
return entityManager.createQuery(query)
.getResultList();
}
}
spring 將嘗試查找帶有 Impl 后綴的接口的實現,這里是UserRepositoryCustomImpl
(接口名稱:UserRepositoryCustom + Impl(postfix))。 如果您更喜歡另一個后綴,您可以在此處的配置中添加@EnableJpaRepositories( repositoryImplementationPostfix = "Impl2", )
Impl2
是您的自定義后綴。 所以你的實現 class 名稱應該是UserRepositoryCustomImpl2
假設您有一個實體Person
。 您為此創建了一個存儲庫接口。
public interface PersonRepository extends JpaRepository<Person, String>{}
然后你需要一個自定義邏輯。 因此,您創建了一個自定義存儲庫接口:
@NoRepositoryBean
public interface CustomPersonRepository {
[...]
}
以及帶有Impl
后綴的 class 的實現:
@Repository
public class CustomPersonRepositoryImpl implements CustomPersonRepository{
@PersistenceContext
private EntityManager entityManager;
[...]
}
現在您將自定義接口添加到原始存儲庫接口:
public interface PersonRepository extends JpaRepository<Person, String>,CustomPersonRepository{
}
當您@Autowired
PersonRepository
接口,並在屬於CustomPersonRepository
的注入 bean 上調用方法時,Spring 將使用CustomPersonRepositoryImpl
的方法。
所以實現的名字 class 必須和自定義接口同名+最后一個Impl
。 無論如何,您都可以使用@EnableJpaRepositories
注釋中的repositoryImplementationPostfix
屬性參數化該后綴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.