Java 检查列表中包含的整数值时,如何处理HQL查询中的空值

Java 检查列表中包含的整数值时,如何处理HQL查询中的空值,java,hibernate,hql,Java,Hibernate,Hql,我拥有的是一个Spring引导存储库,在其中我尝试使用HQL创建一个查询函数 函数接受一个整数参数,如果该参数为null,则查询应忽略该参数,否则,如果列表包含该值,则应检查列表 where子句分为两部分,空检查和列表检查,如下所示: @Service @Transactional public class YourService { // autowired by constructor injection private final YourEntityRepository

我拥有的是一个Spring引导存储库,在其中我尝试使用HQL创建一个查询函数

函数接受一个整数参数,如果该参数为null,则查询应忽略该参数,否则,如果列表包含该值,则应检查列表

where子句分为两部分,空检查和列表检查,如下所示:

@Service
@Transactional
public class YourService {

    // autowired by constructor injection
    private final YourEntityRepository repo;

    public List<YourEntity> getAllYourEntitiesByParam(Long param) {
        if (param == null) {
            return repo.findAll();
        }
        return repo.findAllByParam(param);
    }
}
@Query(“从MyEntity中选择u”+
其中(:myParam为null或(2,3)中的:myParam)
)
现在的问题是,对于(2,3)部分中的
:myParam,它抱怨“不一致的数据类型:预期的二进制数”

(当:myParam为null时,对于:myParam!=null,它工作)

我试过:

  • 将param或null值强制转换为in

  • 使用coalesce(:myParam,CAST(NULL为int))解决了一个类似的问题:myParam是一个整数列表

  • 使用switch-case语句

(当:spracheKy为null时为true,当:spracheKy为(2,3)时为true,否则为false end)=true


提前感谢您的帮助

为什么不使用两种不同的存储库方法,例如,一种不带参数,另一种带参数。然后确定决策逻辑并将其封装在服务层的单独方法中?我指的是基于参数调用哪个存储库方法的逻辑是否为null…可能如下所示:

@Service
@Transactional
public class YourService {

    // autowired by constructor injection
    private final YourEntityRepository repo;

    public List<YourEntity> getAllYourEntitiesByParam(Long param) {
        if (param == null) {
            return repo.findAll();
        }
        return repo.findAllByParam(param);
    }
}
@服务
@交易的
公共服务{
//通过构造函数注入自动连线
私人最终报告回购;
公共列表getAllYourEntitiesByParam(长参数){
if(param==null){
返回回购findAll();
}
返回回购findAllByParam(参数);
}
}

Hi,感谢您的回复:)问题是我要制作一个相对复杂的api,它有大约50个筛选条件,一个整数值只是其中一个。我认为最简单的方法是使用一个查询,每个参数有一行,以保持至少一半的可读性/可维护性。筛选条件类似于-可能id列表中的实体id-实体列表包含特定值(问题就在这里)-实体中的日期大于/小于/等于参数。。。etcpp@Felix好的,我明白了。仅仅通过阅读你的答案,我想知道Hibernate/JPA的CriteriaAPI是否更适合。。。