Spring JPA规范:在父类中搜索参数

问题描述 投票:1回答:1

我似乎无法弄清楚如何使父类params可用于规范查询。如果我使用RoleDAO参数name进行查询,那么我得到一个结果,但如果我尝试搜索数据库中存在的idBaseDAO值,则不会返回任何内容。

另一方面,如果我将id param移动到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;

}

base DAO:

@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)))
        );
java spring-data
1个回答
0
投票

解决方案非常简单:

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()呼叫改变。

© www.soinside.com 2019 - 2024. All rights reserved.