gpt4 book ai didi

jpa - Spring 数据 JPA : get first record using @Query annotation on query method

转载 作者:行者123 更新时间:2023-12-04 14:25:02 25 4
gpt4 key购买 nike

我的查询方法返回实体列表:

@Query("select u from ProfileDMO p inner join p.userPrincipal u where p.id=:profileId")
List<UserPrincipalDMO> findUserPrincipalByProfileId(@Param("profileId") long profileId);

我只需要第一个结果。目前,我正在使用 List.get(int index) 获取第一个元素。

有谁知道我应该如何更新我的查询方法以只返回第一个结果?

最佳答案

更新后的答案:

如果您不能使用派生查询,其中 Spring Data JPA 从方法名称派生查询,您可以使用 Pageable 参数来限制结果,并使用具有默认实现的第二个方法来隐藏参数并解包结果:

@Query("select u from ProfileDMO p inner join p.userPrincipal u where p.id=:profileId")
List<UserPrincipalDMO> internalFindUserPrincipalByProfileId(@Param("profileId") long profileId, Pageable page);

default UserPrincipalDMO findUserPrincipalByProfileId(long profileId){
return internalFindUserPrincipalByProfileId(
profileId,
PageRequest.of(0,1)
).get(0);
};

当然,这会在您的 API 中留下内部实现,如果您不喜欢这样,您总是可以回退到自定义实现。

原答案:

您应该能够使用查询派生,即删除 @Query 注释并将您的方法更改为:

UserPrincipalDMO findFirstByUserPrincipalProfileId(@Param("profileId") long profileId);

如果您不喜欢这个名称,您可以使用带有您喜欢的名称的默认方法并委托(delegate)给我建议的那个。

如果您根本不需要接口(interface)中的方法名称,您可以提供自定义实现。

关于jpa - Spring 数据 JPA : get first record using @Query annotation on query method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47776620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com