0

I have a user repository which is declared like this

public interface UserRepository extends JpaRepository<ApplicationUser, Long> 

In one of the services, I want to get the user and before returning, I want to change the password to dummy text, but I don't want to save that entity.

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

With entity manager I can do getReference and get a copy, but how do I do it with JPARepository?

Should I get the object with findByUsername() and then use its id with getOne() function?

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

1 Answers1

0

You could ask yourself the question: What is the use case for this method?

  • Provide some information about a user (but without password)
  • Authentication (where the password is needed)

Most probably you could omit the password from the mapped fields and offer special methods for verifying against the (hashed and salted) password or changing it.

For the mechanics of how to create a variant of the persisted Entity, have a look at Cloning JPA entity

Stephan
  • 23
  • 4