使用自定义REST控制器中的链接资源与Spring REST JPA

时间:2017-11-13 16:30:38

标签: java spring spring-data-rest spring-hateoas

我正在数据库上开发一组休息资源,并使用Spring Data Rest公开核心CRUD功能,直接与存储库进行交互。

在我的简化示例中,我有用户:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user")
    public Collection<Project> projects;
}

和用户自己的项目:

@Entity
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;

    public String name;

    public String oneOfManyComplexDerivedProperties;

    @ManyToOne
    public User user;
}

直接与存储库交互很好,因此对于创建用户(其他其他简单实体),问题在于创建项目。项目具有大量基于用户表单输入的服务器派生字段,因此我编写了一个自定义控制器来生成它们并保留结果。 为了保持结果,我需要将项目与其拥有的用户相关联。我希望我的客户端能够使用用户链接,就像通过直接访问存储库创建新实体一样(直接到存储库工作):

@RepositoryRestController
public class CustomProjectController {

    @Autowired
    ProjectRepo projectRepo;

    @RequestMapping(value = "/createProject", method = RequestMethod.POST)
    public HttpEntity<Project> createProject(@RequestParam User userResource,
                                         @RequestParam String formField1, // actually an uploaded file that gets processed, but i want simple for example purposes
                                         @RequestParam String formfield2)
{
    Project project = new Project();

    /*
    Actually a large amount of complex business logic to derive properties from users form fields, some of these results are binary.
     */
    String result = "result";
    project.oneOfManyComplexDerivedProperties = result;
    project.user = userResource;
    projectRepo.save(project);

    // aware that this is more complex than I've written.
    return ResponseEntity.ok(project);
}
}

当我打电话时:
http://localhost:9999/api/createProject?userResource=http://localhost:9999/api/users/1&formField1=data1&formField2=Otherdata

我明白了:

{
    "timestamp": 1510588643801,
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException",
    "message": "Failed to convert value of type 'java.lang.String' to required type 'com.badger.User'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Long] for value 'http://localhost:9999/api/users/1'; nested exception is java.lang.NumberFormatException: For input string: \"http://localhost:9999/api/users/1\"",
    "path": "/api/createProject"
}

如果我将userResource更改为Resource类型,那么我会收到不同的错误:
"Failed to convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.hateoas.Resource': no matching editors or conversion strategy found"

我找不到在文档中自定义控制器中使用存储库URI的任何参考,我发现最接近的是Resolving entity URI in custom controller (Spring HATEOAS)但是API已经改变,因为编写后我无法将其转换为工作

3 个答案:

答案 0 :(得分:1)

我建议你应该做的是:

http://localhost:9999/api/users/1/projects?formField1=data1&formField2=Otherdata

通过启用Spring Data的Web支持,您可以将路径变量自动绑定到实体实例。

@RequestMapping(value = "users/{id}/projects", method = RequestMethod.POST)
        public HttpEntity<Project> createProject(
                            @PathVariable("id") User user,
                            @RequestParam String formField1,
                            @RequestParam String formfield2)
{

}

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#core.web

答案 1 :(得分:0)

User userResource需要的是User对象,您传入的是String http://localhost:9999/api/users/1

因此,我建议您将请求更改为POST请求,并将您的用户对象作为该请求的正文传递。

请求的主体看起来像JSON格式:

{
    id: 1,
    name: "myName",
    projects: []
}

然后您从网址中删除userResource=http://localhost:9999/api/users/1。 最后将@RequestParam User userResource更改为@RequestBody User userResource

修改 由于您在请求中拥有用户ID,因此您可以在控制器内拨打电话以通过Id查找用户。因此,您可以将用户对象从@RequestParam User userResource更改为@RequestParam long userId,然后拨打电话,在方法中找到类似findUserById(userId)的用户

所以你的网址看起来像http://localhost:9999/api/createProject?userId=1&formField1=data1&formField2=Otherdata

答案 2 :(得分:0)

如果您想坚持使用网址参数,可以将@RequestParam User userResource更改为@RequestParam String userId

然后在你的createProject代码中有类似

的内容
User user = userRepo.findOne(userId);
project.user = user;
....
projectRepo.save(project);

如果是我,我会定义一个你传入的CreateProjectRequest对象,例如

{
   "userId" : "1",
   "formField1" : "whatever",
   "formField2" : "whatever"
}

将您的createProject更改为

createProject(@RequestBody CreateProjectRequest createProjectRequest)
    ...
    project.setField1(createProjectRequest.getFormField1());
    ...

    User user = userRepo.findOne(createProjectRequest.getUserId());
    project.user = user;
    ....
    projectRepo.save(project);