I have a requirement to construct a dynamic service. I am using Stringbuilder but I am not sure how to use this with JPA repository.
I build an SQL native query using the Stringbuilder.toString() and then pass this to the JPA interface. I get a "syntax error" when I run this. But when I run the same query which I have build using StringBuilder in DBeaver, I am able to get the results.
@Repository
public interface UserRepository extends JpaRepository<User, Long>
@Query(value = ":strQry", nativeQuery = true)
List<User> findUserDetails(@Param("strQry") String strQry);
Those things denoted by a leading colon are "bind parameters" you can only replace expressions with bind parameters, i.e. you can use them where you could also use a literal expression like 23
or 'Shrut Biswas'
.
If you want to construct your SQL statement and execute it you'll have to write a custom method, get an EntityManager
injected and execute something like
em.createNativeQuery(yourSqlStatement).getResultList();
Note: Please read up about SQL injection attacks. The combination of concatenating your own SQL statement and not understanding bind parameters is likely to lead to vulnerabilities.