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)

1
  • Look at EntityManager#createNativeQuery and JdbcOperations#query methods Commented Feb 11, 2022 at 10:44

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

could you add any code examples so i can accept the answer ++1

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.