user8355591
user8355591

Reputation: 201

Hibernate returns Method threw 'org.hibernate.exception.SQLGrammarException' exception. Could not extract ResultSet

I have a piece of code

public List<Fruit> getFruits(final Set<Integer> ids) {
    final Criteria criteria = super.criteria().add(Restrictions.in("id", ids));
    final List<Fruit> fruits = this.list(criteria);  // throws SQLGrammarException
    fruits.forEach(this::initializeFruit);
    return fruits;
}

When empty set provided, it will throw exception in this.list(criteria), 'org.hibernate.exception.SQLGrammarException' exception. Could not extract ResultSet

Any suggestions how can I prevent?

Thanks!

Upvotes: 0

Views: 735

Answers (1)

Smutje
Smutje

Reputation: 18123

Basically this is how JPA is designed

There must be at least one element in the comma separated list that defines the set of values for the IN expression.

And the easiest way how to handle the erroneous situation you mentioned on having an empty list is to skip querying the database altogether because the condition is not supposed to match any entry anyway:

public List<Fruit> getFruits(final Set<Integer> ids) {
    final List<Fruit> fruits;

    if (ids.isEmpty()) {
        fruits = Collections.emptyList();
    } else {
        final Criteria criteria = super.criteria().add(Restrictions.in("id", ids));
        fruits = this.list(criteria);
        fruits.forEach(this::initializeFruit);
    }

    return fruits;
}

Upvotes: 1

Related Questions