io.seventytwo.vaadinjooq.repository.JooqRepository Maven / Gradle / Ivy
package io.seventytwo.vaadinjooq.repository;
import com.vaadin.flow.data.provider.SortDirection;
import org.jooq.*;
import org.jooq.Record;
import org.jooq.impl.DSL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import static com.vaadin.flow.data.provider.SortDirection.ASCENDING;
import static org.jooq.impl.DSL.field;
import static org.jooq.impl.DSL.name;
/**
* Convenience methods using {@link DSLContext}
*/
public class JooqRepository {
private final DSLContext dslContext;
/**
* Requires {@link DSLContext}
*
* @param dslContext The DSLContext to use
*/
public JooqRepository(DSLContext dslContext) {
this.dslContext = dslContext;
}
/**
* Convenience findAll
*
* @param table The table to select from
* @param condition A condition for the where clause
* @param orderBy A map fields for sorting
* @param offset The start offset
* @param limit The number of records to return
* @param The Record type
* @return List of Records
*/
public List findAll(Table table, Condition condition, Map, SortDirection> orderBy, int offset, int limit) {
SelectConditionStep where;
if (condition == null) {
where = dslContext.selectFrom(table)
.where(DSL.noCondition());
} else {
where = dslContext.selectFrom(table)
.where(condition);
}
if (orderBy != null && !orderBy.isEmpty()) {
return createOrderBy(table, where, orderBy)
.offset(offset)
.limit(limit)
.fetch();
} else {
return where
.offset(offset)
.limit(limit)
.fetch();
}
}
/**
* Count method similar to @see findAll
*
* @param table The table to count the records
* @param condition A condition for the where clause
* @param The Record type
* @return Number of records
*/
public int count(Table table, Condition condition) {
if (condition == null) {
return dslContext.fetchCount(dslContext.selectFrom(table));
} else {
return dslContext.fetchCount(dslContext.selectFrom(table).where(condition));
}
}
/**
* Base on map of Fields this method adds an order by
*
* @param table The table
* @param where The where condition
* @param orderColumns The map that contains the order fields
* @param Record type
* @return The select step with the order by clause
*/
private SelectSeekStepN createOrderBy(Table table, SelectConditionStep where, Map, SortDirection> orderColumns) {
List> orderFields = new ArrayList<>();
orderColumns.forEach((key, value) -> {
List qualifiers = new ArrayList<>();
qualifiers.add(table.getSchema().getName());
qualifiers.addAll(Arrays.asList(table.getQualifiedName().getName()));
qualifiers.add(key.getName());
Name column = name(qualifiers);
Field