gpt4 book ai didi

java - Spring JPA规范: searching for parameters in a parent class

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:08 25 4
gpt4 key购买 nike

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

如果另一方面我将 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)))
);

最佳答案

解决方案非常简单:

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() 调用更改。

关于java - Spring JPA规范: searching for parameters in a parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55287741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com