'Spring Data JDBC and specification pattern
We got an Spring Boot 2 application using Spring Data JDBC. Its displaying a list of orders which needs to be filtered for many different aspects and combinations. Therefore, our Repository is growing more and more, because for new combinations find* methods are added or new parameters are applied.
public interface OrderJdbcRepository extends PagingAndSortingRepository<OrderEntity, Long> {
String ORDER_FILTER = "WHERE ..."; // big custom sql statement
String NOT_BILLED = "...";
Optional<OrderEntity> findById(String orderId);
@Query(
"SELECT o.* FROM `ORDER` AS o "
+ ORDER_FILTER
+ "ORDER BY o.ORDER_ID "
+ "LIMIT :limit OFFSET :offset"
)
List<OrderEntity> findFiltered(String customerId, LocalDate startDate,
LocalDate endDate, ...some other filter criterias, int limit, long offset);
@Query(
"SELECT o.* FROM `ORDER` AS o "
+ ORDER_FILTER + NOT_BILLED // additional filter for not billed orders
+ "ORDER BY o.ORDER_ID "
+ "LIMIT :limit OFFSET :offset"
)
List<OrderEntity> findFilteredAndNotBilled(String customerId, LocalDate startDate,
LocalDate endDate, ...some other filter criterias, int limit, long offset);
// many other methods which looks similar
I'm afraid of that this leads to unmaintainable code. Therefore I'm trying to use the composite specification pattern like its described in the link. For example i just need to combine CustomerIdSpecification, DateBetweenSpecification and NotBilledSpecification. However, the linked tutorial is for Spring Data JPA with Criteria API, which does not exist in Spring Data JDBC. So I'm thinking of how i could solve this problem in Spring Data JDBC.
I need a way to define the custom sql in each specification and pass it to my OrderJdbcRepository. An alternative I thought is to use JdbcTemplate for building a custom sql and accessing my data by hand. Are there other solutions, which I did not think of?
Thanks so far!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
