Search code examples
springmongodbspring-data-resthateoasspring-hateoas

Implementing/Overriding MongoRepository Keep HATEOAS Formatting


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?


Solution

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