Implementing/Overriding MongoRepository Keep HATEOAS Formatting

半城伤御伤魂 提交于 2019-12-08 06:22:21

问题


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);
}

I have explored ways to generate the id client side and pass it in the post BUT I really want Spring to handle this.

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);
}

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?


回答1:


Was using @Controller instead of @RepositoryRestController which was causing things to act up.

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);
    }
}



回答2:


Have a look at the interface:

public Employee save(Employee employee)

You can get the saved entity by simply doing

Employee saved = repository.save(employee);
return saved.getId();

The being said, you surely can generate the Id and set it via setId(). But once an ID is saved, it is immutable. Changing the Id and saving that entity would result in a new document saved in MongoDB.



来源:https://stackoverflow.com/questions/26417320/implementing-overriding-mongorepository-keep-hateoas-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!