如何强制Spring DATA REST @PathVariable实体存在

时间:2016-04-28 12:12:31

标签: java spring entity-framework spring-mvc spring-data

对于注入@PathVariable实体我的意思是

@RequestMapping(method = RequestMethod.PUT, path = "{project-id}")
@Transactional
@PreAuthorize("#user.id == #project.userId")
public Object update(@P("user") @Current User user,
                     @P("project") @PathVariable Project entity,
                     @RequestBody @Valid ProjectPost request) {
    setProjectPostToEntity(entity, request);

    return ResponseEntity.ok(ImmutableMap.of("message", "Project update successful"));
}

但是如果在存储库中找不到@PathVariable Project entityproject-id将为null,我想要的是这样的

@RequestMapping(method = RequestMethod.PUT, path = "{project-id}")
@Transactional
@PreAuthorize("#user.id == #project.userId")
public Object update(@P("user") @Current User user,
                     @P("project") @PathVariable @Valid @NotNull(message="Update project not exists") Project entity,
                     @RequestBody @Valid ProjectPost request) {
    setProjectPostToEntity(entity, request);

    return ResponseEntity.ok(ImmutableMap.of("message", "Project update successful"));
}

如果在资源库中找不到project-id会返回消息Update project not exists,但@Valid @NotNull(message="Update project not exists")在此处不起作用,我该怎么办?

1 个答案:

答案 0 :(得分:0)

使用方法setProjectPostToEntity(entity, request)创建服务,并使用@Transactional@PreAuthorize对其进行注释。这种方法保证您的变量将存在。 关于控制器方法的@Transactionalhttps://stackoverflow.com/a/23120647/5649869