Reputation: 395
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 data jpa using @Query annotation and native = true flag.
Is there any way I can write query in repository class and instead of the @Query annotation as the Query is very complex and dynamic.
Upvotes: 10
Views: 26012
Reputation: 121
You need to do a CustomRepository
and add a method with native query.
I do that this way:
Create your custom repository:
public interface OcorrenciaRepositoryCustom {
List<Object[]> getStrings(List<String> valores);
}
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();
}
}
Extend your custom repository from main repository:
public interface OcorrenciaRepository extends JpaRepository<Ocorrencia, Long>, OcorrenciaRepositoryCustom {
Ocorrencia findByPosto(Posto posto);
}
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.
Upvotes: 11