gpt4 book ai didi

java - Spring 增删改查 : how to handle null?

转载 作者:行者123 更新时间:2023-12-01 06:07:04 24 4
gpt4 key购买 nike

我目前使用 Spring (Boot) CrudRepository 接口(interface)来获取我的 Hibernate 实体,在此问题的上下文中使用 findOne(Long id) 方法。

只要我不使用 null 作为 id 调用它,这一切都可以正常工作,在这种情况下,生成的方法会以 NullPointerException 终止。现在我可以轻松地围绕该函数扭曲另一个类来处理该问题,但这有点违背自动化 CRUD 系统的概念。

有没有办法让生成的 Spring 代码以返回 null 而不是异常的方式处理 null ID?

更清楚地说:我有代码围绕它来防止异常。问题在于是否有一种 Spring 方法来处理这个问题,而不是围绕它包装代码。

最佳答案

没有。

看看the doc

Throws: IllegalArgumentException - if id is null

findOne 的逻辑很简单:

  • 如果找不到具有指定 id 的对象,则返回 null
  • 如果调用者不知道 id(即调用者给出 null 参数),它会抛出异常。

问题出在调用“findOne”的代码中,因此您应该尝试修复该问题。

<小时/>

(问题更改后进行编辑)。

(请注意,这并不完全是更改存储库行为的“Spring 方式”,而是将包装代码移动到较低级别的“方式”)

您可以查看AOP with Spring

您可以在 findOne 方法中使用 @Advice @Around 来捕获 IllegalArgumentException(或者更好:测试 null arg 并立即返回 null)。

类似这样的事情:

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;

@Aspect
public class AroundExample {

@Around("com.xyz.myapp.MyRepository.findOne() && args(id)")
public Object hackFindOne(ProceedingJoinPoint pjp, Object id) throws Throwable {
if(id==null) return null;
return pjp.proceed();
}

}

关于java - Spring 增删改查 : how to handle null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42158478/

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