ripper234
ripper234

Reputation: 230156

An easier way to build queries in Play Framework 1.x / JPA using "in"?

Is there a shortcut in Play Framework / JPA to save building this query manually?

public List<User> getAllExceptThese(Collection<String> emails) {
    checkArgument(!emails.isEmpty());

    StringBuilder query = new StringBuilder("email not in (");
    boolean first = true;
    for (String email : emails) {
        if (!first) {
            query.append(", ");
        }
        first = false;
        query.append("?");
    }
    query.append(")");

    return findAll(query.toString(), emails.toArray());
}

Upvotes: 1

Views: 784

Answers (1)

esaj
esaj

Reputation: 16035

I don't know about Play-framework, but if it's possible to create JPQL-queries, how about building a Query-object and using it to insert the collection instead...

  public List<User> getAllExceptThese(Collection<String> emails) {
            checkArgument(!emails.isEmpty());

            String queryStr = "FROM User u WHERE u.email NOT IN (:excludedEmails)";

            Query query = entityManager.createQuery(queryStr);
            query.setParameter("excludedEmails", emails);
            return (List<User>)query.getResultList();
  }

Upvotes: 2

Related Questions