Search code examples
javahibernatehqlcriteria

How to write a criteria or HQL for generic scrollable results in Hibernate?


In my current project of batch processing, I need to write a criteria or HQL for obtain generic scrollable results, in order to process entity one by one. Once processed, the entity id will be saved as checkpoint, called checkpointId. And if the job need to be restarted, then another scrollable query will be created and will be started with the checkpointId. In this batch job, all kinds of entity having @Id are accepted.

If I translate into SQL, it will be similar to the below statement, with FETCH NEXT.

SELECT * FROM my_table WHERE id > checkpoint_id LIMIT 1

If I implement it in Java, it becomes :

Class<?> entityType = MyClass.class;
ScrollableResults scrollableResults = session
        .createCriteria( entityType )
        .setCacheable( false )
        .setFetchSize( 1 )
        //
        // TODO: where id > checkpointId
        //
        .setMaxResults( maxResults )
        .scroll( ScrollMode.FORWARD_ONLY );

But the problems are :

  • How to implement the WHERE condition in Hibernate session ?
  • How to know the identifier type of the current entity ?

I'm using criteria. If HQL is easier, then I can accept HQL. Hibernate version is 5x.


Solution

  • Class<?> entityType = MyClass.class;
    ClassMetadata md = sessionFactory.getClassMetadata( entityType );
    ScrollableResults scrollableResults = session
            .createCriteria( entityType )
            .setCacheable( false )
            .setFetchSize( 1 )
            .add( Restrictions.gt( md.getIdentifierPropertyName(), checkpointId ))
            .setMaxResults( maxResults )
            .scroll( ScrollMode.FORWARD_ONLY );