Spring JPA Технические характеристики: поиск параметров в родительском классе - PullRequest
1 голос
/ 21 марта 2019

Я не могу понять, как сделать параметры родительского класса доступными для запросов спецификации. Если я запрашиваю, используя RoleDAO параметр name, я получаю результат, но если я пытаюсь выполнить поиск по значению id из BaseDAO, присутствующему в БД, то ничего не возвращается.

Если, с другой стороны, я перемещаю параметр id в RoleDAO, тогда поиск работает правильно.

Сущность выглядит так:

@EqualsAndHashCode(callSuper = true)
@Data
@Entity
@Table(name = "user_role", indexes = {
        @Index(name = "id_index", columnList = "id"),
        @Index(name = "name_index", columnList = "name"),
})
public class RoleDAO extends BaseDAO {

    @NotEmpty(message = "{error.not-empty}")
    @Column
    private String name;

}

BaseDAO:

@MappedSuperclass
@Data
public class BaseDAO implements Serializable {

    private static final long serialVersionUID = 1;

    @Id
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @GeneratedValue(generator = "uuid")
    @Column(name = "id", unique = true, nullable = false)
    private String id;

    @NotNull(message = "{error.not-null}")
    @Column(name = "created")
    private LocalDateTime created;

    @NotEmpty(message = "{error.not-empty}")
    @Size(max = 200, message = "{error.max}")
    @Column(name = "created_by")
    private String createdBy;

    @Column(name = "modified")
    private LocalDateTime modified;

    @Size(max = 200, message = "{error.max}")
    @Column(name = "modified_by")
    private String modifiedBy;

    @PrePersist
    public void prePersist() {
        id = UUID.randomUUID().toString();
        created = LocalDateTime.now();
    }

    @PreUpdate
    public void preUpdate() {
        modified = LocalDateTime.now();
    }
}

Спецификация:

public class Specifications<T> {

    public Specification<T> containsTextInAttributes(String text, List<String> attributes) {
        if (!text.contains("%")) {
            text = "%" + text + "%";
        }
        String finalText = text;

        return (root, query, builder) -> builder.or(root.getModel().getDeclaredSingularAttributes().stream()
                .filter(a -> attributes.contains(a.getName()))
                .map(a -> builder.like(root.get(a.getName()), finalText))
                .toArray(Predicate[]::new));
    }
}

Тогда есть хранилище с методом:

List<RoleDAO> findAll(Specification<RoleDAO> spec);

А как это называется в сервисе:

var roles = repository.findAll(
                Specification.where(new Specifications<RoleDAO>().containsTextInAttributes(searchTerm, Arrays.asList(ID, NAME)))
        );

1 Ответ

0 голосов
/ 21 марта 2019

Решение было очень простым:

public class Specifications<T> {

    public Specification<T> containsTextInAttributes(String text, List<String> attributes) {
        if (!text.contains("%")) {
            text = "%" + text + "%";
        }
        String finalText = text;

        return (root, query, builder) -> builder.or(root.getModel().getSingularAttributes().stream()
                .filter(a -> attributes.contains(a.getName()))
                .map(a -> builder.like(root.get(a.getName()), finalText))
                .toArray(Predicate[]::new));
    }
}

Обратите внимание на изменение вызова getSingularAttributes().

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...