0

I prepared a query in serviceImplementation ,After that I passed this query as method argument of presentDaySummarySmscWise(String finalQuery) Repository method. In Repository Interface ,I passed this query with @Query Annotaion like shown in code.

strong text //ServiceImplementation class

@Service

public class ErrorCodeServiceImpl implements ErrorCodeService {

@Autowired

ErrorCodeRepository errorCodeRepo;

@Override

public List<Object[]> errorCodeDefaultSummary() {

String finalQuery="select smsc,vf_reason_code from reason_code_report where 
log_date='2021-05-27'";

List<Object[]> result =   errorCodeRepo.presentDaySummarySmscWise(finalQuery);

return result;

} strong text //Repository

@Repository

public interface ErrorCodeRepository extends JpaRepository<ErrorCodeReportEntity, ErrorCodeReportKeys>{

@Query(value=":query",nativeQuery=true)

List<Object[]> presentDaySummarySmscWise(String query);

}

3
  • You cannot pass a query to a repository method unless you are willing to write a custom repository fragment. Could you please explain why the query needs to be passed as an argument in the first place?
    – crizzis
    May 27, 2021 at 17:12
  • actually , I need a dynamic query in which no of columns can be differ, so i prepared a query based on logic and passed as argument . And in native query to access argument value we use ":argument_variable ". So whole query will be replaced by my passed query. I also tried custom repository fragment but it doesn't work.
    – Aman Singh
    May 27, 2021 at 17:22
  • 1
    If you just want to execute arbitrary queries, JPA repositories are not the correct facility to use.
    – BadZen
    Jun 21, 2021 at 0:16

3 Answers 3

1

You cannot replace arbitrary fragments of the query using a query parameter. Only very specific sections of the query allow parameters.

If you need dynamic queries, Specifications or QueryDSL is what you want.

1
  • can you provide any link or code snippets that suits to my requirement.
    – Aman Singh
    May 28, 2021 at 4:36
0
 @Query("#{[0]}")
 @WithConsistency(QueryScanConsistency.REQUEST_PLUS)
 List<Employee> findByDateAllQuery(String query);
1
  • Answer needs supporting information Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – moken
    Jul 16, 2023 at 6:38
-1

I believe you need to add @Param("query") into your argument in the repository.

List<Object[]> presentDaySummarySmscWise(@Param("query") String query);

1
  • not working, exception from jpa at parameter level. Mar 2, 2023 at 5:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.