Issue
Could someone please explain the difference between these two methods for lists in Hibernate? The name implies that we should use setParameterList for lists, right? But everything works perfectly fine with the setParameter method as well. So what's the difference? I've read the javadoc but it hasn't become clearer why should I prefer this method over the other.
Solution
I guess the difference here in the way of how Hibernate type of the parameter is detected.
- For the
Query<R> setParameterList(String name, Collection values)
method:
Bind multiple values to a named query parameter. The Hibernate type of the parameter is first detected via the usage/position in the query and if not sufficient secondly guessed from the class of the first object in the collection. This is useful for binding a list of values to an expression such as foo.bar in (:value_list).
- For the
Query<R> setParameter(String name, Object value)
method:
Bind a named query parameter using its inferred Type. If the parameter is defined in such a way that the Type cannot be inferred from its usage context then use of this form of binding is not allowed, and
Query.setParameter(String, Object, Type)
should be used instead.
EDIT
As you can see from the implementation of the Query<R> setParameter(String name, Object value)
method:
public QueryImplementor setParameter(String name, Object value) {
getProducer().checkOpen();
if ( value instanceof TypedParameterValue ) {
final TypedParameterValue typedValueWrapper = (TypedParameterValue) value;
setParameter( name, typedValueWrapper.getValue(), typedValueWrapper.getType() );
}
else if ( value instanceof Collection && !isRegisteredAsBasicType( value.getClass() ) ) {
setParameterList( name, (Collection) value );
}
else {
getQueryParameterBindings().getBinding( name ).setBindValue( value );
}
return this;
}
It's equivalent to the setParameterList(String name, Collection values)
method, if value
is Collection
and it's not registered basic type.
Answered By - SternK