Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

java - What's the difference between the IN and MEMBER OF JPQL operators?

What's the difference between the IN and MEMBER OF JPQL operators?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IN tests is value of single valued path expression (persistent attribute of your entity) in values you provided to query (or fetched via subquery).

MEMBER OF tests is value you provided to query (or defined with expression) member of values in some collection in your entity.

Lets's use following example entity:

@Entity
public class EntityA {
    private @Id Integer id;
    private Integer someValue;
    @ElementCollection
    List<Integer> listOfValues;

    public EntityA() { }

    public EntityA(Integer id, Integer someValue, List<Integer> listOfValues) {
        this.id = id;
        this.someValue = someValue;
        this.listOfValues = listOfValues;
    }
}

And following test data:

EntityA a1 = new EntityA(1, 1, Arrays.asList(4, 5, 6));
EntityA a2 = new EntityA(2, 2, Arrays.asList(7, 8, 9));

With following query we get a1 as result, because it's someValue is one of the (0,1,3). Using literals in query (SELECT a FROM EntityA a WHERE a.someValue IN (0, 1, 3)) produces same result.

TypedQuery<EntityA> queryIn = em.createQuery(
    "SELECT a FROM EntityA a WHERE a.someValue IN :values", EntityA.class);
queryIn.setParameter("values", Arrays.asList(0, 1, 3));
List<EntityA> resultIn = queryIn.getResultList();

With following query we get a2 as result, because 7 is one of the values in listOfValues:

TypedQuery<EntityA> queryMemberOf = em.createQuery(
    "SELECT a FROM EntityA a WHERE :value MEMBER OF a.listOfValues", EntityA.class);
queryMemberOf.setParameter("value", 7);
List<EntityA> resultMemberOf = queryMemberOf.getResultList();

This functionality (including collection as parameter) is defined in JPA 2.0 specification and is not specific to Hibernate (above code works for example with EclipseLink).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...