繁体   English   中英

使用 JPARepository 获取实体副本

[英]Getting copy of entity using JPARepository

我有一个像这样声明的用户存储库

public interface UserRepository extends JpaRepository<ApplicationUser, Long> 

在其中一项服务中,我想获取用户,在返回之前,我想将密码更改为虚拟文本,但我不想保存该实体。

ApplicationUser user = userRepository.findByUsername(username);       
user.setPassword("CENSORED");
return user;

使用实体管理器,我可以执行getReference并获取副本,但是如何使用 JPARepository 执行此操作?

我应该使用findByUsername()获取对象,然后将其 id 与getOne()函数一起使用吗?

ApplicationUser user = userRepository.findByUsername(username); 
ApplicationUser user2 = userRepository.getOne(user.getId()); 
user2.setPassword("CENSORED");
return user;

您可以问自己一个问题:此方法的用例是什么?

  • 提供有关用户的一些信息(但没有密码)
  • 身份验证(需要密码的地方)

很可能您可以从映射字段中省略密码并提供特殊方法来验证(散列和加盐)密码或更改它。

有关如何创建持久实体的变体的机制,请查看克隆 JPA 实体

暂无
暂无

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

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