Question

I have a User entity. When I save a user document in the collection I'm hashing the password with @PrePersist but Morphia also calls @PrePersist when I try to update a document without password.

@PrePersist
void prePersist() {
    if (password != null) {
        System.out.println(password);
        PasswordService service = new DefaultPasswordService();
        password = service.encryptPassword(password);
    }
}

This is my update operation.

@Override
public void updateWithoutPassword(T user) {
    Query <T> query = userDAO.createQuery();
    query.and(
            query.criteria("_id").equal(user.getId())
    );
    UpdateOperations <T> updateOperations = userDAO.createUpdateOperations();
    updateOperations.set("username", user.getUsername());
    updateOperations.set("name", user.getName());
    updateOperations.set("surname", user.getSurname());
    updateOperations.set("department", user.getDepartment());
    updateOperations.set("roles", user.getRoles());
    userDAO.update(query, updateOperations);
}

When I call the updateWithoutPassword(), @PrePersist is running and password value is being the old password value and trying to hash the old password again. What am I doing wrong?

Était-ce utile?

La solution

You should probably hash your password in setPassword() instead. @PrePersist will always run.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top