[英]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.