Skip to content

Instantly share code, notes, and snippets.

@dhoss
Created May 26, 2016 19:56
Show Gist options
  • Save dhoss/eb94f0e33138e51c478a033d9e70cc4e to your computer and use it in GitHub Desktop.
Save dhoss/eb94f0e33138e51c478a033d9e70cc4e to your computer and use it in GitHub Desktop.
base service
import org.jooq.Record;
import org.jooq.RecordMapper;
import com.lumos.db.tables.pojos.Images;
import org.jooq.Table;
import java.util.List;
import static com.lumos.db.Tables.IMAGES;
/**
* Created by devin on 3/30/16.
*/
public abstract class BaseService <R extends Record, T extends Table<R>, E>{
protected final int pageSize;
protected final ConfigReader config;
protected Data data;
protected final String uploadPath;
protected final String imageViewPath;
private DSLContext sql;
private Class<E> recordClass;
{ initRecordClass(); }
@SuppressWarnings("unchecked")
private void initRecordClass() {
this.recordClass = (Class<E>) this.getClass();
}
public BaseService(DSLContext s) {
this.data = new Data();
this.config = new ConfigReader();
this.pageSize = Integer.parseInt(this.config.get("pageSize"));
this.uploadPath = this.config.get("imageStorePath");
this.imageViewPath = this.config.get("imageViewPath");
this.sql = s;
}
// I don't want to add a new RecordMapper for each table
protected RecordMapper<Record, Images> imageMapper = r -> {
return new Images(
r.getValue(IMAGES.ID),
r.getValue(IMAGES.NAME),
r.getValue(IMAGES.DESCRIPTION),
r.getValue(IMAGES.DIGEST),
r.getValue(IMAGES.PATH),
r.getValue(IMAGES.GALLERY),
r.getValue(IMAGES.HEIGHT),
r.getValue(IMAGES.WIDTH),
r.getValue(IMAGES.CREATED_ON),
r.getValue(IMAGES.UPDATED_ON)
);
};
protected int getPage(String pageParam) {
int page = 1;
if (pageParam != null) {
page = Integer.parseInt(pageParam);
}
return page;
}
public List<E> list(int pageNumber) {
Page pager = new Page(count());
return sql.select()
.from(table())
.orderBy(table().field("UPDATED_ON").desc(), table().field("CREATED_ON").desc())
.limit(pageSize)
.offset(pager.offsetFromPage(pageNumber))
.fetch()
.into(this.recordClass);
}
public Integer count() {
return (Integer)sql.selectCount()
.from(table())
.fetchOne().getValue(0);
}
// to be implemented by the inheriting class
protected abstract T table();
protected abstract RecordMapper<R, E> mapper();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment