当前位置: 首页 > 知识库问答 >
问题:

使用可选参数删除Spring Boot中的查询

邓建柏
2023-03-14

我试图在Spring Boot中实现删除查询,但是参数是可选的。我如何为相同的数据编写JPA查询。以下是我如何为授权请求参数实施的:

@Transactional
@Repository
public interface ABCRepo extends CrudRepository<ABC, Long>{

public List<ABC> findByABCIdAndStartYrAndStartMonth(String pilotId, int startYr, int startMonth);
public long deleteABCByABCId(String pilotId);
}

Controller.class

@RequestMapping(value="", method= RequestMethod.DELETE)
public Response delete(@PathVariable("abc-id")String pilotId)
{
    LOGGER.info("Trying to delete pilot bank using abc id : "+ abcId);
    long deletedRecords=abcBiz.deleteABCByABCId(abcId);
     if(deletedRecords==0)
     {
        throw new PilotNotFoundException("Entity not found "+abcId);
     }
    return Response.status(Response.Status.NO_CONTENT).entity(deletedRecords).build();
}

添加可选参数后,我的新Controller.class

@RequestMapping(value="", method= RequestMethod.DELETE)
public Response delete(@PathVariable("abc-id")String abcId, @RequestParam(name = "bid-yr", required = false)
        int bidYr, @RequestParam(name = "bid-month", required = false) int bidMonth)
{
    LOGGER.info("Trying to delete pilot bank using abc id : "+ abcId);
    long deletedRecords=abcBiz.deleteABCByABCId(a);bcId
     if(deletedRecords==0)
     {
        throw new PilotNotFoundException("Entity not found "+abcId);
     }
    return Response.status(Response.Status.NO_CONTENT).entity(deletedRecords).build();
}

在JPA我该怎么处理?

共有2个答案

羊舌志
2023-03-14

除了Jignesh所说的之外,别忘了用Param annotation标记参数。此外,jpa修改将返回int/Integer,但不会太长,所以我不得不更改返回类型。

@Modifying
@Query("DELETE FROM ABC WHERE abcId=:pilotId AND (:otherOptionalParam IS NULL OR 
otherField=:otherOptionalParam)")
public long deleteABCByABCId(@Param("pilotId")String pilotId, @Param("otherOptionalParam")String 
otherOptionalParam);
黄毅
2023-03-14

对于可选参数,您需要编写查询。如下所示:

@Modifying
@Query("DELETE FROM ABC WHERE abcId=:pilotId AND (:otherOptionalParam IS NULL OR otherField=:otherOptionalParam)")
public long deleteABCByABCId(String pilotId, String otherOptionalParam);

如果您想要创建一个包含许多可选参数的复杂查询,那么您可以创建自定义存储库,并开发本机查询。在这里,我已经回答了如何在Spring data JPA中创建自定义存储库的问题https://stackoverflow.com/a/68721142/3709922

 类似资料:
  • 在下面的代码中,我有时会将设置为null。此时,它抛出错误为“could not extract resultset;SQL[n/a];嵌套异常为org.hibernate.exception.sqlgrammarexception:could not extract resultset” 即使为空,我如何获取数据。总有一天约会就要来了。这是怎么做的? null

  • 我不明白 FastAPI 中的可选查询参数。它与默认值为 的默认查询参数有何不同? 在下面的示例中,arg1和arg2有什么区别?在该示例中,arg2是一个可选的查询参数,如上面的链接所述。

  • 有什么解决办法吗?有人能帮帮我吗?

  • 问题内容: 我想在存储库层中编写一些查询方法。此方法必须忽略空参数。例如: 在这种情况下,此方法必须返回Foo: 如果gooParam不为null。如果gooParam为null,则条件更改为: 有什么解决办法吗?有人能帮我吗? 问题答案: 来不及了。不确定 Bar 和 Goo 之间的关系。检查 Example是否 可以帮助您。 它为我工作。我有一个类似的情况,实体 用户 具有属性集,并且有基于属

  • 事实上,你可以用raku写以下内容 是惊人的,事实上,参数解析已经为您完成,这是非常有用的。然而,我个人认为非常不符合人体工程学,对于这样的参数,您必须编写一个