我需要在 Spring Boot Web 应用程序中的数据库中的多个表上编写搜索查询。
它使用 spring data jpa。我知道我们可以使用 @Query 注释和 native = true 标志在 spring data jpa 中编写本机查询。
有什么方法可以在存储库类中编写查询而不是 @Query 注释,因为查询非常复杂和动态。
你需要做一个CustomRepository
并添加一个带有本机查询的方法。
我这样做:
-
创建您的自定义存储库:
public interface OcorrenciaRepositoryCustom {
List<Object[]> getStrings(List<String> valores);
}
-
实施您的自定义存储库:
(实现的名称必须是原始存储库的名称添加 Impl 作为后缀。)
public class OcorrenciaRepositoryImpl implements OcorrenciaRepositoryCustom {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Object[]> getStrings(List<String> strings) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT count(o.id) FROM soebm.ocorrencia o WHERE 1=1 ");
if(strings.get(0)!=null && StringUtils.isNotEmpty(strings.get(0))) {
sb.append(" AND to_char(o.date, 'YYYY-MM-DD') >= :dataInicio ");
}
Query query = entityManager.createNativeQuery(sb.toString());
if(strings.get(0)!=null && StringUtils.isNotEmpty(strings.get(0).toString())) {
query.setParameter("dataInicio", strings.get(0));
}
return query.getResultList();
}
}
-
从主存储库扩展您的自定义存储库:
public interface OcorrenciaRepository extends JpaRepository<Ocorrencia, Long>, OcorrenciaRepositoryCustom {
Ocorrencia findByPosto(Posto posto);
}
-
现在,在服务中,您可以从主存储库调用新方法。
@Autowired
private OcorrenciaRepository repository;
public List<Object[]> findOcorrenciaCustom(String str) {
List<String> strings = new ArrayList<String>() {{add(dataInicio);}};
return repository.getStrings(strings);
}
重要的是自定义存储库位于 JpaRepositories 搜索到的包下
@EnableJpaRepositories("com.test.my.repository")
我在本例中使用了 Spring-Data-Jpa 1.9。它在我的项目中完美运行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)