【发布时间】:2018-04-26 10:02:05
【问题描述】:
我正在数据库上开发一组休息资源,并使用 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);
}
}
当我打电话时:@987654321@
我明白了:
{
"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 已经发生了变化,我无法让它工作。
【问题讨论】:
-
User userResource需要的是User对象,您传入的是字符串http://localhost:9999/api/users/1
标签: java spring spring-data-rest spring-hateoas