org.openfact.models.jpa.ScrollAdapter Maven / Gradle / Ivy
package org.openfact.models.jpa;
import org.openfact.models.ScrollModel;
import javax.persistence.TypedQuery;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Function;
public class ScrollAdapter implements ScrollModel {
protected int size;
protected TypedQuery query;
protected Function converter;
protected Class type;
public ScrollAdapter(Class type, TypedQuery query, Function converter) {
this(type, query, converter, 10);
}
public ScrollAdapter(Class type, TypedQuery query, Function converter, int size) {
this.type = type;
this.query = query;
this.converter = converter;
this.size = size;
}
@Override
public Iterator iterator() {
return new PageIterator();
}
class PageIterator implements Iterator {
private int page;
private int pageSize;
private List results;
private int current;
public PageIterator() {
this.page = 1;
this.pageSize = size;
}
@Override
public boolean hasNext() {
if (results == null) {
refreshResults();
}
if (current < results.size()) {
return true;
} else {
if (current == pageSize) {
refreshResults();
return hasNext();
} else {
return false;
}
}
}
@Override
public T next() {
R r = results.get(current++);
if (r == null) {
throw new NoSuchElementException();
}
return (T) converter.apply(type.cast(r));
}
private void refreshResults() {
int start = (page - 1) * pageSize;
results = (List) query.setFirstResult(start).setMaxResults(pageSize).getResultList();
page++;
current = 0;
}
}
}