如何在 Spring Data JPA 中编写动态本机 SQL 查询?

yet*_*der 6 hibernate spring-data-jpa

我需要在 Spring Boot Web 应用程序中对数据库中的多个表编写搜索查询。

它使用弹簧数据 jpa。我知道我们可以使用 @Query 注释和 native = true 标志在 spring 数据 jpa 中编写本机查询。

有什么方法可以在存储库类中编写查询而不是 @Query 注释,因为查询非常复杂和动态。

小智 6

你需要做一个CustomRepository并添加一个带有本机查询的方法。

我这样做:

  1. 创建您的自定义存储库:

    public interface OcorrenciaRepositoryCustom {
       List<Object[]> getStrings(List<String> valores);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 实现你的自定义仓库:(实现的名字必须是原仓库的名字加上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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 从主存储库扩展您的自定义存储库:

    public interface OcorrenciaRepository extends JpaRepository<Ocorrencia, Long>, OcorrenciaRepositoryCustom {
        Ocorrencia findByPosto(Posto posto);
    }
    
    Run Code Online (Sandbox Code Playgroud)
  4. 现在,在服务中,您可以从主存储库调用新方法。

    @Autowired
    private OcorrenciaRepository repository;
    
    public List<Object[]> findOcorrenciaCustom(String str) {
        List<String> strings = new ArrayList<String>() {{add(dataInicio);}};
        return repository.getStrings(strings);
    }
    
    Run Code Online (Sandbox Code Playgroud)

重要的是自定义存储库在 JpaRepositories 搜索的包下

@EnableJpaRepositories("com.test.my.repository")

我在这个例子中使用了 Spring-Data-Jpa 1.9。它在我的项目中完美运行。