How to write a JPA request where parameter is a set?

Assuming the following class, how do you find Person with a specific email address?

 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 this, or is there a proper way?

 select p from Person p where p.email=:email 
+4
source share
2 answers

It is not so easy. JPQL provides an IN statement for this:

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

The "old" way (reading SQL-like):

 select p from Person p join p.email m where m = :email 
+7
source

SQL would look something like this:

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

Unfortunately, I do not know how to do this. If you do this using raw SQL, you need to do this in two steps: create a binding parameter ? for each value in the set, then iterate over the set and bind each value to its binding parameter.

I don't know how to do this in JPA, but this is what you should be looking for.

0
source

All Articles