How to write dynamic native SQL Query in spring data JPA?

后端 未结 1 1030
走了就别回头了
走了就别回头了 2021-01-06 02:54

I need to write a search query on multiple tables in database in spring boot web application.

It uses spring data jpa. I know we can write native query in spring da

相关标签:
1条回答
  • 2021-01-06 03:41

    You need to do a CustomRepository and add a method with native query.

    I do that this way:

    1. Create your custom repository:

      public interface OcorrenciaRepositoryCustom {
         List<Object[]> getStrings(List<String> valores);
      }
      
    2. Implement your custom repository: (The name of the implemantation must be the name of original repository add Impl as suffix.)

      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();
          }
      }
      
    3. Extend your custom repository from main repository:

      public interface OcorrenciaRepository extends JpaRepository<Ocorrencia, Long>, OcorrenciaRepositoryCustom {
          Ocorrencia findByPosto(Posto posto);
      }
      
    4. Now, in the service, you can call your new method from the main repository.

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

    It is important that the custom repository is under the package searched by JpaRepositories

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

    I used Spring-Data-Jpa 1.9 in this example. It worked perfectly in my project.

    0 讨论(0)
提交回复
热议问题