使用 Spring Data JPA 选择一列 [英] Select one column using Spring Data JPA
问题描述
有谁知道如何使用 Spring Data JPA 获取单个列?我在 Spring Boot 项目中创建了一个如下所示的存储库,但在访问 Restful URL 时总是得到 {"cause":null,"message":"PersistentEntity must not be null!"}
错误.
Does anyone have any idea how to get a single column using Spring Data JPA? I created a repository like below in my Spring Boot project, but always get the {"cause":null,"message":"PersistentEntity must not be null!"}
error when accessing the Restful URL.
@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UsersRepository extends CrudRepository<Users, Integer> {
@Query("SELECT u.userName FROM Users u")
public List<String> getUserName();
}
然后,如果我访问像 ../users/search/getUserName
这样的 Restful URL,我会收到错误消息:{"cause":null,"message":"PersistentEntity 不能为空!"}
Then if I access the Restful URL like ../users/search/getUserName
, I get the error:
{"cause":null,"message":"PersistentEntity must not be null!"}
推荐答案
创建投影界面
public interface UserNameOnly {
String getUserName();
}
然后在您的存储库界面中返回该类型而不是用户类型
Then in your repository interface return that type instead of the user type
public interface UserRepository<User> extends JpaRepository<User,String> {
List<UsernameOnly> findNamesByUserNameNotNull();
}
投影接口中的 get 方法必须匹配 JPA 存储库中定义类型的 get 方法,在本例中为 User.findBySomePropertyOnTheObjectThatIsNotNull"允许您根据某些条件获取实体列表(而不是 Iterable),对于 findAll 而言,如果唯一标识符(或任何其他 NonNull 字段)不为空,则可以简单地获取实体列表.
The get method in the projection interface must match a get method of the defined type on the JPA repository, in this case User. The "findBySomePropertyOnTheObjectThatIsNotNull" allows you to get a List of the entities (as opposed to an Iterable) based on some criteria, which for a findAll can simply be if the unique identifier (or any other NonNull field) is not null.
这篇关于使用 Spring Data JPA 选择一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!