繁体   English   中英

JPA 存储库找不到与当前实体相关的现有实体

[英]JPA Repository does not find existing entity with relation to the current entity

我有一个代码可以找到当前登录的用户并通过用户名找到它。

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
MyUserDetails principal = (MyUserDetails) authentication.getPrincipal();
current = userService.findByUsername(principal.getUsername());

在此之后,我试图找到与从UserProfileService返回的当前登录用户相关的实体

 userProfile = userProfileService.findByUser(current);

这对于另一个实体来说工作正常但对于userProfile实体不返回具有userProfile关系的记录

UserProfile 实体字段映射

@OneToOne(mappedBy = "userProfile")
private User user;

对 userProfile 的用户实体字段引用

@OneToOne
@JoinColumn(name = "user_profile_id", referencedColumnName = "id")
private UserPrifile userProfile;

用户配置文件存储库方法

   Optional<UserProfile> findByUser(User user);

这不起作用,因为它没有在数据库中找到具有当前用户关系的用户配置文件。正在为另一个实体工作,但不适用于这个问题的任何线索

编辑:我解决了这个问题,通过用户 ID 而不是用户进行搜索,但仍然不明白为什么不返回记录,因为这对另一个实体有效并返回。

问题不明确。 我们看不到您的存储库和实体类。 您在哪个存储库中使用哪个实体。 请与我们分享。 我想,User Entity 有 UserProfile 实体,所以也许试试;

Optional<User> findByUserProfile(UserProfile userProfile);

在用户存储库上。 因为 User 应该有 UserProfile。 您在 User 实体中有 @OneToOne UserProfile 关系

暂无
暂无

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

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