【发布时间】:2020-11-20 10:42:37
【问题描述】:
大家好,我正在使用带有 MySQL 的 Spring Boot。我尝试查找信息时出现以下错误,
javax.persistence.NonUniqueResultException: 查询没有返回一个 唯一结果:2
在我的 Repository 类中,我有以下代码,
可选的 findByIdOrEmail(Integer id, String email);
我认为错误是因为 findByIdOrEmail 获取多条记录,因为 OR 运算符。
所以我使用List 来获取值,下面是我的代码,我的目标是抛出一个异常,专门显示每个重复值。
List<User> userList = userRepo.findByIdOrEmail(user.getId(), user.getEmail());
// There will be maximum of 2 records fetched by id and email and I didn't
check if each result is the users record
if (!userList.isEmpty() && userList.size() > 1)
throw new CustomException("Duplicate Record Found" +
" id: " + user.getId() + " and email: " + user.getEmail());
else if (!userList.isEmpty())
throw new CustomException("Duplicate Record Found" +
(userList.get(0).getId().equals(user.getId()) ? "id: " + user.getId() : "email: " + user.getEmail()));
所以我想知道这种方法是最好的还是有其他最佳做法?因为用户应该能够更新他/她的记录,但可以检查与现有其他记录的重复项。而且由于它有时会给出一个值列表,所以我必须循环检查它们。那件事是我在上面的代码中没有做过。那么是否有另一种最好的方法或简单的方法来做到这一点而无需循环和多个 if 条件?非常感谢任何答案。提前致谢。
【问题讨论】:
-
你好,看看有没有用dzone.com/articles/…
-
是的,我已经做到了。我用
@ContollerAdvice。但是我只需要上面代码sn-p的解决方案? -
你考虑过 Java 8 流 apis..filter.. 等吗?
-
除此之外还有什么办法吗?
标签: java spring-boot exception spring-data-jpa operators