Search code examples
spring-data-jpanativequery

Native query not working when specifying column name


I am trying to fetch data using native query method. I am able to fetch data using spring data JPA repository declared methods (findAll() etc) and using JPQL Queries.

  • When I am using Native query method , "select * from" is working. But when I am specifying "select username from " method is not working. Means When specifying column name, it is not working.

I am adding my code like this,

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

But the query using select * from users is working with no problem. Is this native query nature? Or is there any limited type of format the provider defines?


Solution

  • I think the problem is with your return variable. When you run "*select * from...*" query, you can return list of Users.

    However, you want to fetch a column which is probably a varchar, so that you should return List of String:

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