简体   繁体   English

无法在springboot和Data JPA中使用nativeQuery方法访问数据记录

[英]Can not accessing data records using nativeQuery method in springboot and Data JPA

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:我尝试使用nativeQuery方法在我的存储库文件中使用Spring BootSpring Data JPA方法在不使用 JPQL 的情况下获取一些数据,我在下面添加了我的示例代码:

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". “出现意外错误(类型=内部服务器错误,状态=500)。无法执行查询;SQL [从用户 u 中选择 u.username];嵌套异常是 org.hibernate.exception.SQLGrammarException:无法执行查询” .

Can anyone help to solve this issue?任何人都可以帮助解决这个问题吗?

You are using nativeQuery which always results in a projection and you try to map that into the List of Users entity.您使用的nativeQuery总是会导致投影,并且您尝试将其映射到Users List实体中。

This wont work, you have expect a List<String> in your case.这行不通,您希望在您的情况下使用List<String> Or List if you decide to add more columns in the result at some point.或者 List 如果您决定在某个时候在结果中添加更多列。

@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 .还要确保数据库中的表实际上是 cassed users并且列是username If you are using the entity name and field name then that is another thing to change.如果您使用实体名称和字段名称,则需要更改另一件事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM