1

I tried nativeQuery method for fetching some data without using JPQL in my repository file using Spring Boot, Spring Data JPA method, I am adding my sample code below:

public interface UsersRepository extends CrudRepository<Users, Long> {
  @Query(value = "select u.username from users u",nativeQuery=true)
  List<Users> findByUsername();
},

And calling the method by,

UsersRepository userRepo;
return (List<Users>) userRepo.findByUsername();

Then the error I am getting:

"There was an unexpected error (type=Internal Server Error, status=500). could not execute query; SQL [select u.username from users u]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query".

Can anyone help to solve this issue?

1 Answer 1

1

You are using nativeQuery which always results in a projection and you try to map that into the List of Users entity.

This wont work, you have expect a List<String> in your case. Or List if you decide to add more columns in the result at some point.

@Query(value = "select u.username from users u",nativeQuery=true)
  List<String> findByUsername();

Also make sure that the table in the database is actually cassed users and the column is username. If you are using the entity name and field name then that is another thing to change.

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

Comments

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.