|
| 1 | +package dev.hilla.crud; |
| 2 | + |
| 3 | +import jakarta.persistence.criteria.CriteriaBuilder; |
| 4 | +import jakarta.persistence.criteria.CriteriaQuery; |
| 5 | +import jakarta.persistence.criteria.Expression; |
| 6 | +import jakarta.persistence.criteria.Path; |
| 7 | +import jakarta.persistence.criteria.Predicate; |
| 8 | +import jakarta.persistence.criteria.Root; |
| 9 | + |
| 10 | +import java.time.LocalDate; |
| 11 | +import java.time.LocalDateTime; |
| 12 | +import java.time.LocalTime; |
| 13 | +import java.time.format.DateTimeFormatter; |
| 14 | +import java.time.temporal.TemporalAccessor; |
| 15 | + |
| 16 | +import dev.hilla.crud.filter.PropertyStringFilter; |
| 17 | +import org.springframework.data.jpa.domain.Specification; |
| 18 | + |
| 19 | +public class PropertyStringFilterSpecification<T> implements Specification<T> { |
| 20 | + |
| 21 | + private PropertyStringFilter filter; |
| 22 | + private Class<T> entity; |
| 23 | + private Class<?> javaType; |
| 24 | + |
| 25 | + public PropertyStringFilterSpecification(PropertyStringFilter filter, |
| 26 | + Class<T> entity, Class<?> javaType) { |
| 27 | + this.filter = filter; |
| 28 | + this.entity = entity; |
| 29 | + this.javaType = javaType; |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, |
| 34 | + CriteriaBuilder criteriaBuilder) { |
| 35 | + String value = filter.getFilterValue(); |
| 36 | + Path<String> propertyPath = root.get(filter.getPropertyId()); |
| 37 | + if (javaType == String.class) { |
| 38 | + Expression<String> expr = criteriaBuilder.lower(propertyPath); |
| 39 | + switch (filter.getMatcher()) { |
| 40 | + case EQUALS: |
| 41 | + return criteriaBuilder.equal(expr, value.toLowerCase()); |
| 42 | + case CONTAINS: |
| 43 | + return criteriaBuilder.like(expr, |
| 44 | + "%" + value.toLowerCase() + "%"); |
| 45 | + } |
| 46 | + |
| 47 | + throw new IllegalArgumentException( |
| 48 | + "Matcher of type " + filter.getMatcher() + " is unknown"); |
| 49 | + } else if (javaType == LocalDate.class) { |
| 50 | + TemporalAccessor date = DateTimeFormatter.ISO_DATE.parse(value); |
| 51 | + return criteriaBuilder.equal(propertyPath, LocalDate.from(date)); |
| 52 | + } else if (javaType == LocalTime.class) { |
| 53 | + TemporalAccessor date = DateTimeFormatter.ISO_TIME.parse(value); |
| 54 | + return criteriaBuilder.equal(propertyPath, LocalDate.from(date)); |
| 55 | + } else if (javaType == LocalDateTime.class) { |
| 56 | + TemporalAccessor date = DateTimeFormatter.ISO_DATE_TIME |
| 57 | + .parse(value); |
| 58 | + return criteriaBuilder.equal(propertyPath, LocalDate.from(date)); |
| 59 | + } else { |
| 60 | + return criteriaBuilder.equal(propertyPath, value.toLowerCase()); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments