Server-side processing with Spring MVC

Server-side processing with Spring MVC

darrachequesnedarrachequesne Posts: 3Questions: 0Answers: 0
edited August 2015 in Free community support

Hi guys !

Recently I had to integrate DataTables within a Spring MVC application (for paging, ordering and filtering data on the server-side). Long story short, I isolated the part of the code relative to the request handling and pushed it to Github, as it may help others. I also uploaded it to Maven Central for more ease of use :

<dependency>
    <groupId>com.github.darrachequesne</groupId>
    <artifactId>spring-data-jpa-datatables</artifactId>
    <version>1.1</version>
</dependency>

HOW TO

  • Add the dependency to your pom.xml
  • Enable the use of DataTablesRepository with:
@EnableJpaRepositories(repositoryFactoryBeanClass = DataTablesRepositoryFactoryBean.class)
  • Make your repositories extend the interface DataTablesRepository:
public interface UserRepository extends DataTablesRepository<User, Integer> {
}
  • Use the repositories to handle DataTables requests:
@RestController
public class UserRestController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/data/users", method = RequestMethod.GET)
    public DataTablesOutput<User> getUsers(@Valid DataTablesInput input) {
        return userRepository.findAll(input);
    }
}
  • Add jquery.spring-friendly.min.js (to allow Spring to properly handle DataTables requests arguments)
  • Finally, on the client-side:
$(document).ready(function() {
    var table = $('table#sample').DataTable({
        'ajax' : '/data/users',
        'serverSide' : true,
        columns : [ // the columns definition matching the User class attributes ]
    });
}

You can then use table.fnFilter() to filter the columns:

  • simple "value" becomes the following clause: WHERE attribute LIKE '%' + value + '%'
  • collection "ONE+TWO" becomes: WHERE attribute IN(ONE, TWO)

Please see the sample Spring Boot project. Do not hesitate to comment, raise issue or suggest an improvement (like integer sorting) !

This discussion has been closed.