Get Your DB Model as a Method Parameter in Your Controller

Last Update: 07.09.2017. By Jens in Spring Boot | Spring MVC | Spring Data

In your Spring MVC application, you will usually have at least one endpoint which accepts and ID as a path variable or request parameter, and often the next thing you will do is to load the model from your Spring Data repository. However, there is an easier way as you will see in a minute.

Spring Data’s DomainClassConverter

Like the pagination in a previous tutorial, Spring Data also offers a way to directly load your model in a Spring MVC controller. The DomainClassConverter helps Spring MVC to resolve repository managed models from request parameters or path variables.

First, enable the web support by adding the @EnableSpringDataWebSupport annotation on your @Configuration class; can be your main or a specific for your web configuration.

Second, use your model as a type of your method parameter and either annotate it as a path variable or a request parameter.

@GetMapping("/comment/{id}")
public CommentModel getComment(@PathVariable(value = "id") CommentModel comment) {
    //do something
    return comment;
}

What happens here now is, that MVC will detect that the path variable id is mapped to our method parameter. It will then look for a converter being able to convert from the path variable to the declared type (CommentModel). DomainClassConverter is such a candidate. It will check if the declared type (CommentModel) is supported by any known Repository and then tries to receive the model instance by using the findOne or findById (latest) method.

In the example above, you will either get an instance of the model or null. However, you also could wrap the model in a Optional, and it will work accordingly in Java 8 Spring Data version.

@GetMapping("/comment/{id}")
public CommentModel getComment(@PathVariable(value = "id") Optional<CommentModel> comment) {
    //do something
    return comment.orElse( ... );
}

Conclusion

It’s an easy to use feature and saves you a couple of lines. However, it is not the way for you when situation is more complex than directly accessing a repository.