0

This is my Class

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Email
    @NotEmpty
    private String email;

    @NotEmpty
    private String password;

    @Transient
    @NotEmpty
    private String passwordConfirmation;
    //constructors, getters, setters omitted....
   }

As you can see, the passwordConfirmation is Transient and will not exist on the equivalent table.

I have a UserRepository that save and retrieve User from the database.

public interface UserRepository extends JpaRepository<MyUser, Long> {}

when I save a user

User user1 = new User("zak@gmail.com", "pass", "pass");
userRepository.save(user1);

Everything works fine, but when I retrieve the User for some processing I'm getting a javax.validation.ConstraintViolationException: Validation failed for classes

  User user1 = userRepository.findByUsername("zak@gmail.com");
  //some procesing
  userRepository.save(user1);

When I retrieve the User, the passwordConfirmation get a null value, and for that reason I'm getting this exception.

What could be a good solution for my scenario. Should I reset the passwordConfirmation value.

xmen-5
  • 1,806
  • 1
  • 23
  • 44
  • 2
    *"What could be a good solution?"* Remove `@NotEmpty` since that's the constraint that is begin violated. I'm confused you're even asking. You never care if it is empty or not. If validating UI, you care if it is same as `password`, otherwise you don't care at all. In reality, the field shouldn't exist, since the double-password inputs is to guard against typo's and should be checked in the web browser, not on the server. – Andreas Sep 17 '19 at 20:35
  • @Andreas it's not a dumb question, may be it's antipattern, but I tried to use entity as controller input param and I need the transient field to be validated. but for me it's not clear why a persistance layer tries to validate it if it's invisible for him and I got an error during load from db – Yura Jun 04 '23 at 22:36

1 Answers1

1

passwordConfirmation is marked as @NotEmpty, so you're doing a get, but not retrieving any value from the database, then saving the record which fails @NotEmpty constraint you've set up. Remove the constraint or set it to a value.

Jake Luby
  • 1,718
  • 5
  • 16