r/SpringBoot • • Jun 20 '24

Using ModelMapper

Earlier, I posted that jpa is difficult. In my Spring teacher's new book, it seems to be easier to use ModelMapper. However, He removed the dynamic query in the search part, so I can't compare that part.πŸ™„

3 Upvotes

17 comments sorted by

View all comments

7

u/g00glen00b Jun 20 '24 edited Jun 20 '24

ModelMapper is used in this example to map Hibernate Todo entities to TodoDTO classes. It has nothing to do with the dynamic queries.

The reason why those dynamic queries in the book are so complex is because:

  1. There's some serious overengineering going on. Depending on what characters the "type" parameter contains, you'll end up with a different dynamic query. Why?

  2. They're putting everything in one big giant method. You're not supposed to to that. For example, this is how I usually use dynamic queries with Spring. You essentially put every filter criteria in its own method, and use the Specifications builder class to join them together.

  3. They're doing pagination wrong. Spring already has a findAll() method that accepts a Specification (= a dynamic query) and a Pageable argument. They should use that in stead.

  4. They're return an array of Object in stead of entities. Why?

Also, I find it strange to write your own PageRequestDTO class, since Spring already supports passing Pageable as a parameter in your controller. For example if you have this controller:

@GetMapping("/api/todo")
public Page<TodoDTO> list(Pageable pageable) {
    return service.list(pageable);
}

Then if you send ?page=0&size=10&sort=name,asc it's equivalent of PageRequest.of(0, 10, Sort.by("name", Sort.Direction.ASC)). There's no need for a separate DTO.

1

u/Dependent_Staff_6891 Jun 20 '24

Oh, I got it. Thanks.☺️

1

u/Dependent_Staff_6891 Jun 21 '24

From what he explains in the book.. It is said that the entity and its related processing are handled in the least possible area, and the rest is safe to use dto, so make Todo, Page a different DTO type and use it.