Aman Singh
Aman Singh

Reputation: 29

How to pass complete query as String in repository method as argument and use with the @Query Annotation?

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);

}

Upvotes: 0

Views: 3526

Answers (3)

prguptadev
prguptadev

Reputation: 50

 @Query("#{[0]}")
 @WithConsistency(QueryScanConsistency.REQUEST_PLUS)
 List<Employee> findByDateAllQuery(String query);

Upvotes: 0

Beez
Beez

Reputation: 532

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

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

Upvotes: -1

crizzis
crizzis

Reputation: 10726

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.

Upvotes: 1

Related Questions