使用Spring JPA在IN子句中使用多个列来创建Postgres查询

a6b3iqyw  于 7个月前  发布在  Spring
关注(0)|答案(1)|浏览(84)

下面是一个简化的PostgreSQL数据库“构造”表:
| ID|模型|地位|不相关列|
| --|--|--|--|
| 1 |待决定|抛弃|一些数据|
| 2 |待决定|完成|一些数据|
| 3 |旧型号|抛弃|一些数据|
| 4 |旧型号|完成|一些数据|
在Postgres中,我可以通过以下方式选择列:

select c.id from construction c
    where (c.model, c.status) in (
        ('TO_BE_DECIDED', 'ABANDONED'),
        ('OLD_MODEL', 'COMPLETE') )

字符串
我会返回以下行:
| ID|
| --|
| 1 |
| 4 |
如何使用Spring JPA(非原生或原生查询)调用这样的查询,其中我可以将IN条件作为List传递?其他要求:
1.我不想使用像连接到单个值这样的技巧,这样数据库索引仍然被使用。
1.在IN子句中可以使用2个以上的列,例如5个。
我尝试在@Query语句中传递List,但我得到的是QuerySyntaxException,而不是包含值1和4的List:

@Query("select c.id " +
        "from Construction c " +
        "where (c.model, c.status) in (:filter.model, :filter.status)"
    )
    List<Long> getConstructions(@Param("filter") List<ConstructionFilter> filter);


哪里

@Builder
    @Getter
    @Setter
    public class ConstructionFilter {
        private String model;
        private String status;
    }

jq6vz3qz

jq6vz3qz1#

如果你正在检索实体,我会说解决方案是:

public interface Construction Repository extends CrudRepository<Construction, Long>, JpaSpecificationExecutor<Construction> {

    default List<Construction> getConstructions(List<ConstructionFilter> filter) {
        Specification<Construction> specification = (root, cq, cb) -> cb.or(
                filter.stream().map(f -> cb.and(
                        cb.equal(root.get("model"), f.getModel()),
                        cb.equal(root.get("status"), f.getModel())
                )).toArray(Predicate[]::new)
        );
        return findAll(specification);
    }

}

字符串
不幸的是,这不允许只检索id,实现customfragment存储库可能会有所帮助。

相关问题