gpt4 book ai didi

java.lang.IllegalArgumentException : No enum constant found

转载 作者:行者123 更新时间:2023-12-04 16:23:52 25 4
gpt4 key购买 nike

我有这个枚举,我想用它来设置不同的状态:

@Enumerated(EnumType.STRING)
@Column(name = "status", length = 20)
private OnboardingTaskStatus status;

public enum OnboardingTaskStatus {
NEW,
IN_PROGRESS,
DISABLED,
}
当我尝试构建搜索规范时,我得到了这个:
public Page<OnboardingTaskDto> findOnboardingTasks(OnboardingTaskSearchParams params, Pageable pageable){
Specification<OnboardingTasks> spec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
if (params.getStatus() != null) {
predicates.add(cb.equal(root.get("status"), params.getStatus()));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
};
return onboardingTasksService.findAll(spec, pageable).map(onboardingMapper::taskToTaskDTO);
}

@Getter
@Setter
public class OnboardingTaskSearchParams {
private String title;
private String status;

private LocalDateTime createdAt;
private LocalDateTime updatedAt;
}
我尝试将状态更新为该文件:
predicates.add(cb.equal(root.get("status"), OnboardingTaskStatus.valueOf(params.getStatus())));
但我得到错误:

OnboardingTaskStatus.2769df0841; nested exception is java.lang.IllegalArgumentException: No enum constant OnboardingTaskStatus.2769df0841] with root causejava.lang.IllegalArgumentException: No enum constant OnboardingTaskStatus.2769df0841


如果找不到值,您是否知道实现 Enum 搜索而不抛出错误的正确方法是什么?

最佳答案

您可以在 Enum 中引入静态方法检查给定字符串是否正确 Enum值(value)。像这样的东西,

enum OnBoardingTaskStatus {
NEW,
IN_PROGRESS,
DISABLED;

public static Optional<OnBoardingTaskStatus> check(String val) {
try { return Optional.of(OnBoardingTaskStatus.valueOf(val)); }
catch (Exception e) {/* do nothing */}
return Optional.empty();
}
}
注意这里我返回了一个 Optional那你可以换 findOnboardingTasks方法如下,
public Page<OnboardingTaskDto> findOnboardingTasks(OnboardingTaskSearchParams params, Pageable pageable) {
Specification<OnboardingTasks> spec = (root, query, cb) -> {
List<Predicate> predicates = new ArrayList<>();
predicates.add(cb.notEqual(cb.literal(1), 1));

OnBoardingTaskStatus.check(params.getStatus())
.ifPresent(e -> predicates.add(cb.equal(root.get("status"), e)));

return cb.or(predicates.toArray(new Predicate[]{}));
};
return onboardingTasksService.findAll(spec, pageable).map(onboardingMapper::taskToTaskDTO);
}

关于java.lang.IllegalArgumentException : No enum constant found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69163458/

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