I want to implement a PATCH-Requese on an entity 'User' for changing the password with an additional transient property 'oldpassword' to compare it in the EventHandler.
The POST- and the PUT-request fill the property.
The PATCH-request doesn't: 'oldpassword' is null.
I'm using
- spring-boot-starter-parent
- spring-boot-starter-data-rest (2.1.6)
- spring-boot-starter-web (2.1.6)
- spring-boot-starter-data-jpa (2.1.6)
- spring-data-jpa 2.1.9
- spring-data-rest 3.1.9
- spring-security 5.1.5 (presumably irrelevant)
I tried
- the annotation @JsonProperty("oldpassword") (even though POST and PUT work).
- the annotation @JsonDeserialize (JSON: @Transient field not seralizing)
- to configure Jackson to disable the check for @Transient annotations (JPA Transient Annotation and JSON)
- @JsonAutoDetect(fieldVisibility = Visibility.ANY) as class decorator
The simplified code is:
The entity 'User'
@Entity
public class User implements UserDetails, Serializable {
[...]
@NotNull
String password;
@Transient
String newpassword;
@Transient
String oldpassword;
public void setPassword(String password) {
this.newpassword = password;
}
public void setOldpassword(String oldpassword) {
this.oldpassword = oldpassword;
}
[...]
}
The Repository
@RepositoryRestResource(exported = true)
public interface UserRepository extends JpaRepository<User, Long> {
}
PATCH-Request (
HTTP Method = PATCH
Request URI = /api/users/2
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Authorization:"Basic aXJ0Z2VuZGFhczpFaW4gcGFzc3dvcmQ="]
Body = {
"username": "myusername",
"password": "mynewpassword",
"oldpassword": "theoldone"
}
The EventHandler
@Component
@RepositoryEventHandler(User.class)
public class UserEventHandler {
@HandleBeforeSave
public void printdata(User p) {
/* returns the new password*/
System.out.println("newpassword" + p.newpassword);
/* returns null (if it's a PATCH-request) */
System.out.println("oldpassword" + p.oldpassword);
/* returns the old persisted password */
System.out.println("password" + p.password);
}
}
The transient property 'newpassword' works, since I use the setter of the persisted property 'password'.