问题描述
我有一个简单的MongoRepository,我想对其进行修改以在post(save())上返回生成的ObjectId.
I have a simple MongoRepository I would like to modify to return the generated ObjectId on post(save()).
public interface EmployeeRepository extends MongoRepository<Employee, String>
{
public void delete(Employee employee);
public Employee save(Employee employee);
public Employee findOne(String id);
public List<Employee> findAll();
public Employee findByName(String principal);
}
我已经探索了生成id客户端并在发布后传递的方法,但我真的希望Spring能够处理此问题.
I have explored ways to generate the id client side and pass it in the post BUT I really want Spring to handle this.
我尝试用控制器进行拦截并在ResponseBody中返回对象,如下所示:
I've tried intercepting with a controller and returning the object in the ResponseBody, like so:
@RequestMapping(value=URI_EMPLOYEES, method=RequestMethod.POST)
public @ResponseBody Employee addEmployee(@RequestBody Employee employee) {
return repo.save(employee);
}
这个问题是它迫使我重新设计Spring为我处理的与HATEOAS相关的所有逻辑.这是一个主要的痛苦. (除非我缺少任何东西.)
Problem with this is it forces me to re-work all the HATEOAS related logic Spring handles for me. Which is a MAJOR pain. (Unless I'm missing something.)
无需替换所有方法的最有效方法是什么?
What's the most effective way of doing this without having to replace all of the methods?
推荐答案
正在使用 @Controller 而不是 @RepositoryRestController ,这导致事情发生了.
Was using @Controller instead of @RepositoryRestController which was causing things to act up.
我们现在可以轻松覆盖此资源上的POST方法,以返回我们想要的任何内容,同时保持spring-data-rest的EmployeeRepository实现完好无损.
We can now easily override the POST method on this resource to return whatever we want while keeping spring-data-rest's implementation of the EmployeeRepository intact.
@RepositoryRestController
public class EmployeeController {
private final static String URI_EMPLOYEES = "/employees";
@Autowired private EmployeeRepository repo;
@RequestMapping(value=URI_EMPLOYEES, method=RequestMethod.POST)
public @ResponseBody HttpEntity<Employee> addVideo(@RequestBody Employee employee) {
return new ResponseEntity<Employee>(repo.save(employee), HttpStatus.OK);
}
}
这篇关于实施/覆盖MongoRepository保持HATEOAS格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!