【发布时间】:2019-11-29 15:33:31
【问题描述】:
我想在实体“用户”上实现 PATCH-Requese,以使用附加的临时属性“旧密码”更改密码,以便在 EventHandler 中进行比较。
POST 和 PUT 请求填充属性。
PATCH 请求没有:'oldpassword' 为空。
我正在使用
- 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
- 弹簧数据休息 3.1.9
- spring-security 5.1.5(可能不相关)
我试过了
- 注释 @JsonProperty("oldpassword")(即使 POST 和 PUT 有效)。
- 注解@JsonDeserialize (JSON: @Transient field not seralizing)
- 配置 Jackson 以禁用检查 @Transient 注释 (JPA Transient Annotation and JSON)
- @JsonAutoDetect(fieldVisibility = Visibility.ANY) 作为类装饰器
简化代码为:
实体“用户”
@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;
}
[...]
}
存储库
@RepositoryRestResource(exported = true)
public interface UserRepository extends JpaRepository<User, Long> {
}
补丁请求(
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"
}
事件处理程序
@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);
}
}
瞬态属性“newpassword”有效,因为我使用了持久属性“password”的设置器。
【问题讨论】:
-
向 SDR 报告为错误。 @Transient 注解不会反序列化 MongoRepository PATCH 请求 [DATAREST-1524] 上的字段。 github.com/spring-projects/spring-data-rest/issues/1881
-
DATAREST-1524 - 使用设置器修复瞬态字段的反序列化。第381章github.com/spring-projects/spring-data-rest/pull/381
-
太好了,感谢您提供的信息。我放弃了这种方法。但很高兴知道。
标签: spring spring-data-rest transient http-patch