psql中ANY运算符的等效JPA查询

时间:2019-05-08 05:52:17

标签: hibernate jpa persistence

我有一个看起来像这样的实体。我已出于简化目的删除了某些字段:

@Entity    
public class ObjectMeta implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "inc_id", columnDefinition = "SERIAL")
private Integer id;

@Column(nullable = false, unique = true)
private String name;
    @Column(name = "status", columnDefinition = "verification_status DEFAULT 'PENDING' NOT NULL")
private String status;

@Column(name = "categories", columnDefinition = "character varying (10)[]")
@Type(type = "stringUserType")
private List<String> categories;
@UpdateTimestamp
@Column(name = "modified_on", columnDefinition = "TIMESTAMP WITHOUT TIME ZONE DEFAULT now() NOT NULL")
@Temporal(TemporalType.TIMESTAMP)
private Date modifiedOn;
@Column(name = "modified_by", columnDefinition = "character varying(100)")
private String modifiedBy;
}

现在,我有一个API,可根据字段名称Modify_by,modified_on查询该实体。另外,在其他字段上也有类似于以下代码中为该名称添加的谓词的谓词。这是我当前功能的简化版本:

@Transactional
public List<AdomainMeta> getObjects(final String like, final String category) {
    final EntityManager em = getEntityManager();
    final CriteriaBuilder cb = em.getCriteriaBuilder();

    final CriteriaQuery<ObjectMeta> criteriaQuery = cb.createQuery(ObjectMeta.class);

    final Root<ObjectMeta> metaRoot = criteriaQuery.from(ObjectMeta.class);
    final List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.like(cb.lower(metaRoot.get("name")),like.toLowerCase()));

    criteriaQuery.where(predicates.toArray(new Predicate[] {}));

    final TypedQuery<ObjectMeta> typedQuery = em.createQuery(criteriaQuery);
    return typedQuery.getResultList();
}

上面的功能等同于下面的psql查询:

select * from object_meta where name like '%like%';

我只想添加一个谓词以使此函数等效于以下psql查询:

select * from object_meta where name like '%like%' and 'category' = ANY(categories);

我曾尝试在JPA中搜寻与psql ANY运算符等效的内容,但没有发现任何实质内容。任何帮助表示赞赏。还有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

尝试in

predicates.add(cb.in(cb.parameter(String.class, "cat")));
... // non-empty collection. not array
typedQuery.setParameter("cat", categoryCollection);

在PostgreSQL中,表达式a IN (b,c,e)在内部转换为a = ANY(ARRAY[b,c,e]),而a NOT IN (b,c,e)变成a <> ALL (ARRAY[b,c,e])

但是,似乎您正在寻找错误的运算符。您是否希望它包含参数中的任何一个或全部?因为anyarray = ANY(anyarray)无法正常工作。