Issue with grid.getDataProvider()

After using the grid.setItems() method, I’m trying to get the first item from the grid and for that I use grid.getDataProvider().fetch(new Query<>()).findFirst()

The problem now is, it is executing two queries

select
        i1_0.id,
        i1_0.item_name,
        i1_0.sku 
    from
        item i1_0 
    where
        lower(i1_0.item_name) like '%fg%' escape '!' 
    limit
        0, 2147483647

and

 select
        i1_0.id,
        i1_0.item_name,
        i1_0.sku 
    from
        item i1_0 
    where
        lower(i1_0.item_name) like '%fg%' escape '!' 
    limit
        0, 50

The first query is trying to all items though paging is already set. If this approach is not correct, how do I get hte first item from the grid ? I tried gridLazyDataView.getItems().findFirst() and it also does the same.

The problem here is, that the grid itself does not store all items internally, but reads the 50 items to be displayed and discards them, when the next set of items is read. And since your data provider seems to be lazy loading, the dp also has no information about all available items .

If you pass in a query without any additional parameters, the Vaadin simply pass this query to your implementation, which then will do its thing - in your case, asking the database for the full set of data. The second query is most likely the normal grid query, that is called during grid init time.

If you want to use the data provider as a source, you need to pass a more specific query. The easiest way is to let the data communicator build the query for you as it takes care of applying the current grid sorting and filter.

var query = grid.getDataCommunicator().buildQuery(0, 1);
var optionalItem = grid.getDataProvider().fetch(query).findFirst();

You might want to check your use case anyway, if it might make more sense to use the service / repository directly to check for the first item, e.g. by providing a specific method for that with a specialized sql query

Are you using Vaadin 14. Then what you are trying is sort of correct direction and completed by Stefan in the next reply. But if you are using Vaadin 23 or 24 there is better API for this.

        var dataView = grid.setItems(items);
        var item = dataView.getItem(0);

I’m using V24. What if there are no items returned and dataView.getItem(0) throw an error ? ArrayIndex issue ?

hmm. Querying the table again is the safest way ?

Then dataView.getItems() == 0.