简体   繁体   English

如何编写JPA查询,其中参数是一个集合?

[英]How to write JPA query where parameter is a set?

Assuming the following class, how do you find a Person with a particular email address? 假设下面的类,你如何找到一个Person与一个特定的电子邮件地址?

public class Person implements Comparable<Person> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="id")
    private long id = 0;

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE}, fetch=FetchType.LAZY)
    private Set<String> email = new HashSet<String>();
}

Is it as simple as doing just this, or is there a proper way? 它就像做这个一样简单,还是有正确的方法?

select p from Person p where p.email=:email

It's not that easy. 那并没那么简单。 JPQL provides the IN operator for this: JPQL为此提供了IN运算符:

select p from Person p, IN(p.email) m where m = :email

The 'old' way (read SQL-like) would be: “旧”方式(读取类似SQL)将是:

select p from Person p join p.email m where m = :email

The SQL would look something like this: SQL看起来像这样:

WHERE email IN ('foo@yahoo.com', 'bar@gmail.com')

Unfortunately, I'm not aware of an easy way to do this. 不幸的是,我不知道有一种简单的方法可以做到这一点。 If you were doing this with raw SQL, you'd have to do it in two steps: create a bind parameter ? 如果您使用原始SQL执行此操作,则必须分两步执行此操作:创建绑定参数? for each value in the set, then iterate through the set and bind each value to its bind parameter. 对于集合中的每个值,然后遍历集合并将每个值绑定到其绑定参数。

I'm not aware of a way to do it cleanly in JPA, but that's what you should be looking for. 我不知道在JPA中干净利落的方法,但这就是你应该寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM