【问题标题】:Delete Query in Spring Boot with Optional Parameter使用可选参数在 Spring Boot 中删除查询
【发布时间】:2021-09-15 19:47:02
【问题描述】:

我正在尝试在 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);
}

控制器类

@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 处理这个问题?

【问题讨论】:

    标签: java spring-boot jpa


    【解决方案1】:

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

    @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

    【讨论】:

    • 调试并检查所有传递给这个存储库方法的参数值。您在上述评论中所述的查询似乎没有问题。
    • 以下是值:("5422", null, null, null),这些值将进入存储库方法
    • 但是我怎么知道这些值是否存在于您的数据库中。检查数据库中的这些值。
    • 5422 确实存在,但没有包含 bidyear 或 bidabbrev 的列和 bidmonth 与 5422 匹配的空值。我的问题是如果为空值,我如何才能忽略这些字段并且只忽略具有价值的字段。
    • 通过上述查询,它们默认被忽略。 (:bidYr IS NULL OR startYr=:bidYr) 如果bidYr 参数是null,这将忽略startYr 比较。
    【解决方案2】:

    除了Jignesh 所说的,别忘了用Param 注释标记你的参数。 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);
    

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2021-09-15
      • 2020-02-27
      • 1970-01-01
      • 2020-10-21
      • 2012-07-21
      • 2020-05-31
      • 1970-01-01
      • 2023-02-04
      相关资源
      最近更新 更多