JPA Select "Where IN"

460 views
Skip to first unread message

Barsum

unread,
Sep 17, 2011, 5:16:40 AM9/17/11
to play-framework
Q1:

I've made this JPA query that I find really satisfying:

Booking.find("SELECT DISTINCT b FROM Booking b JOIN b.participants AS
t WHERE t = ?", person).fetch();

This query is used for finding all bookings where a given person
participates - and it works just fine.

But now I would like to extend the query so that it will take a list
of employees:

I've tried:

List<Person> persons = Person.findAll();
Booking.find("SELECT DISTINCT b FROM Booking b JOIN b.participants AS
t WHERE t IN ?", persons).fetch();

Which gives me the error:
JPAQueryException occured : Error while executing query SELECT
DISTINCT b FROM Booking b JOIN b.participants AS t WHERE t IN ?:
org.hibernate.HibernateException: Unable to resolve entity name from
Class [java.util.ArrayList] expected instance/subclass of
[models.Person]

I've also tried:

List<Long> ids = new ArrayList<Long>();
ids.add(employee.id);
Booking.find("SELECT DISTINCT b FROM Booking b JOIN b.participants AS
t WHERE t.id IN ?", ids)

Which gives me the error:
JPAQueryException occured : Error while executing query SELECT
DISTINCT b FROM Booking b JOIN b.participants AS t WHERE t.id IN ?:
java.util.ArrayList cannot be cast to java.lang.Long

Heureka! While writing this post, I found a solution. Using the
EntityManager:

List<Person> persons = Person.findAll();
Query query = JPA.em().createQuery("SELECT DISTINCT b FROM Booking b
JOIN b.participants AS t WHERE t IN (?1)");
query.setParameter(1, persons);

So am I using Play JPA wrong? Or is it a missing feature to use WHERE
IN with ? parameteres.

Q2:
Do you have good references where to read about JPA? With lots of
examples :)


Tex

unread,
Sep 17, 2011, 9:51:34 AM9/17/11
to play-fr...@googlegroups.com
Try this 

IN (?1) 

seems that positional parameter worka well with "in clause"...

List<Long> ids = new ArrayList<Long>(); 
ids.add(employee.id); 
List<Booking> bookings = Booking.find("SELECT DISTINCT b FROM Booking b JOIN b.participants AS t WHERE t.id IN (?1)", ids).fetch();

Barsum

unread,
Sep 17, 2011, 6:52:44 PM9/17/11
to play-framework
Thanks Tex - you're absolutely right.

While reading about JPA I came across NamedQueries, and they
supposedly perform better than dynamic queries, so now I'm considering
using EntityManager anyway. Is there any drawbacks to NamesQueries
other than the more cluttered syntax?

Tex

unread,
Sep 18, 2011, 3:51:41 PM9/18/11
to play-fr...@googlegroups.com
Sorry Barsum I cannot answer your question (I'm mainly a Ruby on Rails programmer and I'm not a JPA expert...)

Reply all
Reply to author
Forward
0 new messages