1

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 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'.

Bla Blubb
  • 23
  • 4
  • Reported as bug to SDR. @Transient annotation won't deserialize fields on MongoRepository PATCH requests [DATAREST-1524]. https://github.com/spring-projects/spring-data-rest/issues/1881 – pdorgambide Feb 04 '21 at 23:50
  • 1
    DATAREST-1524 - Fix deserialization of transient fiels with setters. #381. https://github.com/spring-projects/spring-data-rest/pull/381 – pdorgambide Feb 04 '21 at 23:59
  • Great, thanks for the information. I dropped the approach. But it is nice to know. – Bla Blubb Feb 06 '21 at 09:39

1 Answers1

0

It seems you want to create a change-password feature. It won't work this way. Create a unique controller method for it.

It's not a standard REST request anyway.

Selindek
  • 3,269
  • 1
  • 18
  • 25