1

I am aware about how spring data jpa allows using native queries.

@Query(
  value = "SELECT * FROM USERS u WHERE u.status = 1", 
  nativeQuery = true)
Collection<User> findAllActiveUsersNative();

Reference - https://www.baeldung.com/spring-data-jpa-query

But my interest here is, instead of using the SQL with @Query annotation, it is possible to execute the sql query programmatically (for example say how we do while using jdbc) and get result in to a dto or resultset.

I just want to explore above approach for cases where the query might be generated dynamically and may not be know at compile time.

I have seen sof posts, which suggests other approaches like QueryByExample and QueryDSL and i know using JPA Specification also this case can be addressed. And these are great and the right way of addressing dynamic query situation.

But in this Q, I am interested in knowing if SQL queries can be executed programmatically (not through @Query annotation). If yes, how? (some demo code will help)

joven
  • 371
  • 1
  • 6
  • 17

1 Answers1

2

Well, you can always write a repository extension, into which you can inject the EntityManager.

crizzis
  • 9,978
  • 2
  • 28
  • 47