繁体   English   中英

How to load authenticated users's entity model from Spring Data JPA using Spring security to use in other JPA Repositories?

[英]How to load authenticated users's entity model from Spring Data JPA using Spring security to use in other JPA Repositories?

我有一个UserEntity model 和相应的UserRepository. 同样,我有BookEntity model 和BookRepository 书与用户有@ManyToOne关系。

因此,在 Book 实体中,有一个字段使用@ManyToOne注释映射到用户实体的 id 作为 FK。 当我想根据用户检索书籍列表时,我调用方法List<BookEntity> findByUser(UserEntity user); 来自BookRepository ,使用 Spring 数据 JPA。

我可以在 Spring 安全性的帮助下加载当前经过身份验证的用户,但这给了我一个UserDetails object。 我需要的是UserEntity object 以便我可以将它传递给BookRepository方法。

现在,正在做的是调用Optional<UserEntity> findByUsername(String username); UserRepository获取UserEntity并执行此操作,我从 Spring 安全提供的UserDetails实例获取用户名。 然后将此UserEntity model 传递给BookRepository方法。

我想知道这是否是加载UserEntity model 以传递到BookRepository的正确方法,还是有其他方法可以这样做? 如果不是,我是否错误地将书籍映射到用户?

任何帮助将不胜感激。

在您的 BookRepository 中执行类似的操作

@Query("FROM Book b where b.user.userName = :userName")
List<Book> findBooksForUser(@Param("userName") String userName);

您可以在 controller 中获取当前用户用户名,例如

@RequestMapping(value = "/books", method = RequestMethod.GET)
@ResponseBody
public String getBooks(Authentication authentication) {
  if(authentication != null){
    //Call bookRepo.findBooksForUser(authentication.getName())
  }

  ....
}

暂无
暂无

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

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