Now I will explain another solution in which you can use a regular query and pagination method without having problems with possible duplicates or suppressed elements.
This solution has the advantage of:
- faster than PK id solution mentioned in this article.
- saves the order and does not use the "in" parameter on the largest possible data set PK
The full article can be found on my blog.
Hibernate provides the ability to define an association selection method not only at design time, but also at run time by executing a query. Thus, we use this aproach in combination with simple interception tools and can also automate the process of changing the query properties selection algorithm for collection properties only.
First, we create a method that resolves all the properties of the collection from the Entity class:
public static List<String> resolveCollectionProperties(Class<?> type) { List<String> ret = new ArrayList<String>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(type); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if (Collection.class.isAssignableFrom(pd.getPropertyType())) ret.add(pd.getName()); } } catch (IntrospectionException e) { e.printStackTrace(); } return ret; }
After that, you can use this small helper method, advising your criteria object to change the FetchMode to SELECT in this query.
Criteria criteria = β¦ // β¦ add your expression here β¦ // set fetchmode for every Collection Property to SELECT for (String property : ReflectUtil.resolveCollectionProperties(YourEntity.class)) { criteria.setFetchMode(property, org.hibernate.FetchMode.SELECT); } criteria.setFirstResult(firstResult); criteria.setMaxResults(maxResults); criteria.list();
Doing this is different from defining the FetchMode of your objects at design time. That way, you can use the usual associative binding using swap algorithms in the user interface, because in most cases this is not a critical part, and it is more important that your results are as fast as possible.
Andreas Hartmann-schneevoigt Jul 06 2018-12-12T00: 00Z
source share