Hibernate Criteria API - 添加标准:字符串应该在集合中 [英] Hibernate Criteria API - adding a criterion: string should be in collection

查看:79
本文介绍了Hibernate Criteria API - 添加标准:字符串应该在集合中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须跟随实体对象



@Entity
public class Foobar {
    ...
    private List<String> uuids;
    ...
}

现在我想要制作一个标准查询,可以获取其uuids列表中包含字符串abc123的所有Foobar pojos,我只是不确定如何制作相应的标准。

Now I'd like to make a criteria query which would fetch all Foobar pojos whose uuids list contains the string "abc123", I'm just not sure how to make the appropriate criterion.

推荐答案

我假设您使用的是实现JPA 2.0的Hibernate版本。这是一个JPA 2.0解决方案,适用于任何兼容的实现。

I assume you are using a version of Hibernate that implements JPA 2.0. Here's a JPA 2.0 solution that should work with any compliant implementation.

请使用JPA的<$ c $注释 uuids c> @ElementCollection 注释。不要像其他一些答案评论中提到的那样使用Hibernate的 @CollectionOfElements 。后者具有相同的功能,但被弃用

Please annotate uuids with JPA's @ElementCollection annotation. Don't use Hibernate's @CollectionOfElements as mentioned in some of the other answer comments. The latter has equivalent functionality but is being deprecated.

Foobar.java 看起来大致如下:

@Entity
public class Foobar implements Serializable {

    // You might have some other id
    @Id
    private Long id;

    @ElementCollection
    private List<String> uuids;

    // Getters/Setters, serialVersionUID, ...

}

以下是如何构建 CriteriaQuery 以选择所有 Foobar uuids 包含abc123。

Here's how you can build a CriteriaQuery to select all Foobars whose uuids contain "abc123".

public void getFoobars() {
{
    EntityManager em = ... // EM by injection, EntityManagerFactory, whatever

    CriteriaBuilder b = em.getCriteriaBuilder();
    CriteriaQuery<Foobar> cq = b.createQuery(Foobar.class);
    Root<Foobar> foobar = cq.from(Foobar.class);

    TypedQuery<Foobar> q = em.createQuery(
            cq.select(foobar)
              .where(b.isMember("abc123", foobar.<List<String>>get("uuids"))));

    for (Foobar f : q.getResultList()) {
        // Do stuff with f, which will have "abc123" in uuids
    }
}

我在玩这个时制作了一个独立的概念验证程序。我现在不能把它推出去。如果你想把POC推到github,请评论。

I made a self-contained proof-of-concept program while playing with this. I can't push it out right now. Please comment if you want the POC pushed to github.

这篇关于Hibernate Criteria API - 添加标准:字符串应该在集合中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆