下面列出了怎么用org.hibernate.criterion.Projection的API类实例代码及写法,或者点击链接到github查看源代码。
private HashMap<Long, ArrayList<VisitScheduleItem>> listExpandDateModeByProband(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to)
throws Exception {
ProjectionList proj = Projections.projectionList();
proj.add(Projections.id());
Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, null).values().iterator();
while (sqlColumnsIt.hasNext()) {
proj.add(sqlColumnsIt.next());
}
visitScheduleItemCriteria.setProjection(proj);
HashMap<Long, ArrayList<VisitScheduleItem>> result = new HashMap<Long, ArrayList<VisitScheduleItem>>();
Iterator it = visitScheduleItemCriteria.list().iterator();
while (it.hasNext()) {
Object[] row = (Object[]) it.next();
probandId = (Long) row[4];
ArrayList<VisitScheduleItem> visitScheduleItems;
if (result.containsKey(probandId)) {
visitScheduleItems = result.get(probandId);
} else {
visitScheduleItems = new ArrayList<VisitScheduleItem>();
result.put(probandId, visitScheduleItems);
}
visitScheduleItems.add(getVisitScheduleItemFromRow(row));
}
CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
return result;
}
@Override
public List<Long> getUnassignedDocumentIDsByCrisisID(Long crisisID, Integer count) {
List<Long> docIDList = new ArrayList<Long>();
Criteria criteria = null;
try {
String aliasTable = "taskAssignments";
String order = "ASC";
String aliasTableKey = "taskAssignments.id.documentId";
String[] orderBy = {"valueAsTrainingSample", "documentId"};
Criterion criterion = Restrictions.conjunction()
.add(Restrictions.eq("collection.id",crisisID))
.add(Restrictions.eq("hasHumanLabels",false));
// get just the documentIDs
Projection projection = Projections.property("documentId");
Criterion aliasCriterion = (Restrictions.isNull(aliasTableKey));
criteria = createCriteria(criterion, order, orderBy, count, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN);
docIDList = criteria.list();
return docIDList;
} catch (Exception e) {
logger.error("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString(), e);
throw new HibernateException("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString());
}
}
/**
* Get the names of the columns constrained
* by this criterion.
*/
@Override
public String[] getColumnsUsingProjection(
Criteria subcriteria,
String propertyName) throws HibernateException {
//first look for a reference to a projection alias
final Projection projection = rootCriteria.getProjection();
String[] projectionColumns = null;
if ( projection != null ) {
projectionColumns = ( projection instanceof EnhancedProjection ?
( ( EnhancedProjection ) projection ).getColumnAliases( propertyName, 0, rootCriteria, this ) :
projection.getColumnAliases( propertyName, 0 )
);
}
if ( projectionColumns == null ) {
//it does not refer to an alias of a projection,
//look for a property
try {
return getColumns( propertyName, subcriteria );
}
catch ( HibernateException he ) {
//not found in inner query , try the outer query
if ( outerQueryTranslator != null ) {
return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName );
}
else {
throw he;
}
}
}
else {
//it refers to an alias of a projection
return projectionColumns;
}
}
@Override
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName)
throws HibernateException {
//first look for a reference to a projection alias
final Projection projection = rootCriteria.getProjection();
Type[] projectionTypes = projection == null ?
null :
projection.getTypes( propertyName, subcriteria, this );
if ( projectionTypes == null ) {
try {
//it does not refer to an alias of a projection,
//look for a property
return getType( subcriteria, propertyName );
}
catch ( HibernateException he ) {
//not found in inner query , try the outer query
if ( outerQueryTranslator != null ) {
return outerQueryTranslator.getType( subcriteria, propertyName );
}
else {
throw he;
}
}
}
else {
if ( projectionTypes.length != 1 ) {
//should never happen, i think
throw new QueryException( "not a single-length projection: " + propertyName );
}
return projectionTypes[0];
}
}
@Override
public Criteria setProjection(Projection projection) {
this.projection = projection;
this.projectionCriteria = this;
setResultTransformer( PROJECTION );
return this;
}
@Override
public Criteria setProjection(Projection projection) {
CriteriaImpl.this.projection = projection;
CriteriaImpl.this.projectionCriteria = this;
setResultTransformer(PROJECTION);
return this;
}
private ArrayList<VisitScheduleItem> listExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
org.hibernate.criterion.Criterion or, SubCriteriaMap criteriaMap, PSFVO psf, boolean distinct) throws Exception {
// projection to avoid multiplebagexception and get calculated dates
ProjectionList proj = Projections.projectionList();
proj.add(Projections.id());
Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or).values().iterator();
while (sqlColumnsIt.hasNext()) {
proj.add(sqlColumnsIt.next());
}
// populate result collection
CriteriaUtil.applyPSFVO(criteriaMap, psf); //apply filter, populate rowcount
visitScheduleItemCriteria.setProjection(proj); //set projection for final .list()
HashSet<Long> dupeCheck = new HashSet<Long>();
ArrayList<VisitScheduleItem> result = new ArrayList<VisitScheduleItem>();
Iterator it = visitScheduleItemCriteria.list().iterator();
while (it.hasNext()) {
Object[] row = (Object[]) it.next();
if (!distinct || dupeCheck.add((Long) row[0])) {
result.add(getVisitScheduleItemFromRow(row));
}
}
// support sorting by start/stop
AssociationPath sortFieldAssociationPath = new AssociationPath(psf != null ? psf.getSortField() : null);
if (sortFieldAssociationPath.isValid()) {
String sortProperty = sortFieldAssociationPath.getPropertyName();
if ("start".equals(sortProperty)) {
Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_COMPARATOR_START_ASC : VISIT_SCHEDULE_ITEM_COMPARATOR_START_DESC);
} else if ("stop".equals(sortProperty)) {
Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_COMPARATOR_STOP_ASC : VISIT_SCHEDULE_ITEM_COMPARATOR_STOP_DESC);
}
}
// prevent vo caching to substitute unintentionally because of nonunique id's
CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
return result;
}
private ArrayList<Object[]> listExpandDateModeProband(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
SubCriteriaMap criteriaMap, PSFVO psf)
throws Exception {
ProjectionList proj = Projections.projectionList();
proj.add(Projections.id());
Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, null).values().iterator();
while (sqlColumnsIt.hasNext()) {
proj.add(sqlColumnsIt.next());
}
CriteriaUtil.applyPSFVO(criteriaMap, psf);
visitScheduleItemCriteria.setProjection(proj);
ArrayList<Object[]> result = new ArrayList<Object[]>();
Iterator it = visitScheduleItemCriteria.list().iterator();
while (it.hasNext()) {
Object[] row = (Object[]) it.next();
probandId = (Long) row[4];
result.add(new Object[] {
getVisitScheduleItemFromRow(row),
probandId != null ? this.getProbandDao().load(probandId) : null
});
}
AssociationPath sortFieldAssociationPath = new AssociationPath(psf != null ? psf.getSortField() : null);
if (sortFieldAssociationPath.isValid()) {
String sortProperty = sortFieldAssociationPath.getPropertyName();
if ("start".equals(sortProperty)) {
Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_START_ASC : VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_START_DESC);
} else if ("stop".equals(sortProperty)) {
Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_STOP_ASC : VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_STOP_DESC);
}
}
CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
return result;
}
private static Timestamp maxStopExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
org.hibernate.criterion.Criterion or) throws Exception {
ProjectionList proj = Projections.projectionList();
LinkedHashMap<String, Projection> sqlColumns = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or);
proj.add(Projections.sqlProjection(
"greatest(max({alias}.stop), max(" + ((SQLProjection) sqlColumns.get("tagStop")).getSql() + "), max(" + ((SQLProjection) sqlColumns.get("durationStop")).getSql()
+ ")) as maxStop",
new String[] { "maxStop" },
new org.hibernate.type.Type[] { Hibernate.TIMESTAMP }));
visitScheduleItemCriteria.setProjection(proj);
return (Timestamp) visitScheduleItemCriteria.uniqueResult();
}
private static Timestamp minStartExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
org.hibernate.criterion.Criterion or) throws Exception {
ProjectionList proj = Projections.projectionList();
LinkedHashMap<String, Projection> sqlColumns = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or);
proj.add(Projections.sqlProjection(
"least(min({alias}.start), min(" + ((SQLProjection) sqlColumns.get("tagStart")).getSql() + ")) as minStart",
new String[] { "minStart" },
new org.hibernate.type.Type[] { Hibernate.TIMESTAMP }));
visitScheduleItemCriteria.setProjection(proj);
return (Timestamp) visitScheduleItemCriteria.uniqueResult();
}
/**
* Get the names of the columns constrained
* by this criterion.
*/
public String[] getColumnsUsingProjection(
Criteria subcriteria,
String propertyName) throws HibernateException {
//first look for a reference to a projection alias
final Projection projection = rootCriteria.getProjection();
String[] projectionColumns = projection == null ?
null :
projection.getColumnAliases( propertyName, 0 );
if ( projectionColumns == null ) {
//it does not refer to an alias of a projection,
//look for a property
try {
return getColumns( propertyName, subcriteria );
}
catch ( HibernateException he ) {
//not found in inner query , try the outer query
if ( outerQueryTranslator != null ) {
return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName );
}
else {
throw he;
}
}
}
else {
//it refers to an alias of a projection
return projectionColumns;
}
}
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName)
throws HibernateException {
//first look for a reference to a projection alias
final Projection projection = rootCriteria.getProjection();
Type[] projectionTypes = projection == null ?
null :
projection.getTypes( propertyName, subcriteria, this );
if ( projectionTypes == null ) {
try {
//it does not refer to an alias of a projection,
//look for a property
return getType( subcriteria, propertyName );
}
catch ( HibernateException he ) {
//not found in inner query , try the outer query
if ( outerQueryTranslator != null ) {
return outerQueryTranslator.getType( subcriteria, propertyName );
}
else {
throw he;
}
}
}
else {
if ( projectionTypes.length != 1 ) {
//should never happen, i think
throw new QueryException( "not a single-length projection: " + propertyName );
}
return projectionTypes[0];
}
}
/**
* 获取分页记录CriteriaQuery 老方法final int allCounts =
* oConvertUtils.getInt(criteria
* .setProjection(Projections.rowCount()).uniqueResult(), 0);
*
* @param cq
* @param isOffset
* @return
*/
public PageList getPageList(final CriteriaQuery cq, final boolean isOffset) {
Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
getSession());
CriteriaImpl impl = (CriteriaImpl) criteria;
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
final int allCounts = ((Long) criteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
// 判断是否有排序字段
if (cq.getOrdermap() != null) {
cq.setOrder(cq.getOrdermap());
}
int pageSize = cq.getPageSize();// 每页显示数
int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
pageSize);// 当前页
int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
String toolBar = "";
if (isOffset) {// 是否分页
criteria.setFirstResult(offset);
criteria.setMaxResults(cq.getPageSize());
if (cq.getIsUseimage() == 1) {
toolBar = PagerUtil.getBar(cq.getMyAction(), cq.getMyForm(),
allCounts, curPageNO, pageSize, cq.getMap());
} else {
toolBar = PagerUtil.getBar(cq.getMyAction(), allCounts,
curPageNO, pageSize, cq.getMap());
}
} else {
pageSize = allCounts;
}
return new PageList(criteria.list(), toolBar, offset, curPageNO,
allCounts);
}
/**
* 返回JQUERY datatables DataTableReturn模型对象
*/
public DataTableReturn getDataTableReturn(final CriteriaQuery cq,
final boolean isOffset) {
Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
getSession());
CriteriaImpl impl = (CriteriaImpl) criteria;
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
final int allCounts = ((Long) criteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
// 判断是否有排序字段
if (cq.getOrdermap() != null) {
cq.setOrder(cq.getOrdermap());
}
int pageSize = cq.getPageSize();// 每页显示数
int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
pageSize);// 当前页
int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
if (isOffset) {// 是否分页
criteria.setFirstResult(offset);
criteria.setMaxResults(cq.getPageSize());
} else {
pageSize = allCounts;
}
DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(), cq
.getField().split(","), cq.getEntityClass(), false);
return new DataTableReturn(allCounts, allCounts, cq.getDataTables()
.getEcho(), criteria.list());
}
/**
* 返回easyui datagrid DataGridReturn模型对象
*/
public DataGridReturn getDataGridReturn(final CriteriaQuery cq,
final boolean isOffset) {
Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
getSession());
CriteriaImpl impl = (CriteriaImpl) criteria;
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
final int allCounts = ((Long) criteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
if (StringUtils.isNotBlank(cq.getDataGrid().getSort())) {
cq.addOrder(cq.getDataGrid().getSort(), cq.getDataGrid().getOrder());
}
// 判断是否有排序字段
if (!cq.getOrdermap().isEmpty()) {
cq.setOrder(cq.getOrdermap());
}
int pageSize = cq.getPageSize();// 每页显示数
int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
pageSize);// 当前页
int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
if (isOffset) {// 是否分页
criteria.setFirstResult(offset);
criteria.setMaxResults(cq.getPageSize());
} else {
pageSize = allCounts;
}
// DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(),
// cq.getField().split(","), cq.getClass1(), false);
List list = criteria.list();
cq.getDataGrid().setResults(list);
cq.getDataGrid().setTotal(allCounts);
return new DataGridReturn(allCounts, list);
}
/**
* Description: <br>
*
* @author 王伟<br>
* @taskId <br>
* @param detachedCriteria
* @param pi
* @param pageSize
* @param <T> T
* @return T
* @throws DaoException <br>
*/
@Override
public <T> PagerList<T> getPageList(final DetachedCriteria detachedCriteria, final int pi, final int pageSize)
throws DaoException {
int pageIndex = pi;
if (pi == 0) {
pageIndex = 1;
}
Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());
// 查询分页总数
CriteriaImpl impl = (CriteriaImpl) criteria;
Projection projection = impl.getProjection();
Long allCounts = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
criteria.setProjection(projection);
criteria.setFirstResult((pageIndex - 1) * pageSize);
criteria.setMaxResults(pageSize);
PagerList<T> resultList = new PagerList<T>();
resultList.setPageIndex(pageIndex);
resultList.setPageSize(pageSize);
if (allCounts == null) {
allCounts = 0L;
}
resultList.setTotalCount(allCounts);
if (allCounts > 0) {
resultList.addAll(criteria.list());
}
return resultList;
}
/**
* find projection from criteria.
*
* @param criteria
* Criteria
* @return Projection
*/
public static Projection findProjection(Criteria criteria) {
if (criteria instanceof CriteriaImpl) {
return ((CriteriaImpl) criteria).getProjection();
} else {
throw new IllegalArgumentException(criteria
+ " is not a CriteriaImpl");
}
}
/**
* 分页查询函数,使用已设好查询条件与排序的<code>Criteria</code>.
*
* @param criteria
* 条件
* @param pageNo
* 当前页号
* @param pageSize
* 每页最大记录数
* @return 含总记录数和当前页数据的Page对象.
*/
@Transactional(readOnly = true)
public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) {
Assert.notNull(criteria);
Assert.isTrue(pageNo >= 1, "pageNo should be eg 1");
Assert.isTrue(criteria instanceof CriteriaImpl);
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = HibernateUtils.findProjection(criteria);
List orderEntries = HibernateUtils.findOrderEntries(criteria);
HibernateUtils.setOrderEntries(criteria, Collections.EMPTY_LIST);
// 执行查询
Integer totalCount = this.getCount(criteria);
// 将之前的Projection和OrderBy条件重新设回去
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
HibernateUtils.setOrderEntries(criteria, orderEntries);
// 返回分页对象
if (totalCount < 1) {
return new Page();
}
int start = (pageNo - 1) * pageSize;
List result = criteria.setFirstResult(start).setMaxResults(pageSize)
.list();
Page page = new Page(result, totalCount);
page.setPageNo(pageNo);
page.setPageSize(pageSize);
return page;
}
public Criteria createCriteria(Criterion criterion,
String order, String[] orderBy, Integer count, String aliasTable,
Criterion aliasCriterion, Projection[] projections, JoinType joinType) {
Session session = getCurrentSession();
List fetchedList = new ArrayList();
//logger.info("Entity: " + entityClass + ", current Session = " + session);
Criteria criteria = session.createCriteria(entityClass);
criteria.add(criterion);
criteria.createAlias(aliasTable, aliasTable, joinType).add(aliasCriterion);
if (orderBy != null) {
for(int i = 0; i< orderBy.length; i++){
if (order != null && order.equalsIgnoreCase("desc")) {
criteria.addOrder(Order.desc(orderBy[i]));
} else {
criteria.addOrder(Order.asc(orderBy[i]));
}
}
}
if(count != null && count > 0){
criteria.setMaxResults(count);
}
// set projections
setProjections(criteria, projections);
return criteria;
}
private void setProjections(Criteria criteria, Projection[] projections) {
ProjectionList projList = Projections.projectionList();
if(projections != null && projections.length > 0) {
for(Projection projection : projections) {
projList.add(projection);
}
criteria.setProjection(projList);
}
}
@Override
public Integer getDocumentCountForNominalLabelAndCrisis(Long nominalLabelID, String crisisCode) {
if (nominalLabelID != null) {
String aliasTable = "documentNominalLabels";
String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
String[] orderBy = {"documentId"};
Criteria criteria = null;
try {
CollectionDTO cdto = crisisEJB.getCrisisByCode(crisisCode);
Criterion criterion = Restrictions.conjunction()
.add(Restrictions.eq("collection.id",cdto.getCrisisID()))
.add(Restrictions.eq("hasHumanLabels", true));
Criterion aliasCriterion = Restrictions.eq(aliasTableKeyField, nominalLabelID);
// get just the documentIDs
Projection projection = Projections.property("documentId");
//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
criteria = createCriteria(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN);
List<Long> docIDList = criteria.list();
if (docIDList != null && !docIDList.isEmpty()) {
return docIDList.size();
}
} catch (Exception e) {
logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
return 0;
}
}
return 0;
}
@Override
public List<DocumentDTO> getDocumentForNominalLabelAndCrisis(List<Long> nominalLabelID, Long crisisId) {
List<DocumentDTO> dtoList = new ArrayList<DocumentDTO>();
if (nominalLabelID != null) {
String aliasTable = "documentNominalLabels";
String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
Criteria criteria = null;
try {
Criterion criterion = Restrictions.conjunction()
.add(Restrictions.eq("collection.id", crisisId))
.add(Restrictions.eq("hasHumanLabels", true));
Criterion aliasCriterion = Restrictions.in(aliasTableKeyField, nominalLabelID);
// get just the documentIDs
Projection projection = Projections.property("documentId");
//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
criteria = createCriteria(criterion, null, null, null, aliasTable, aliasCriterion, null, JoinType.INNER_JOIN);
List<Document> docList = criteria.list();
if (docList != null && !docList.isEmpty()) {
for (Document doc : docList) {
DocumentDTO dto = new DocumentDTO(doc);
dtoList.add(dto);
}
}
} catch (Exception e) {
logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
}
}
return dtoList;
}
/**
* 获取分页记录CriteriaQuery 老方法final int allCounts =
* oConvertUtils.getInt(criteria
* .setProjection(Projections.rowCount()).uniqueResult(), 0);
*
* @param cq
* @param isOffset
* @return
*/
public PageList getPageList(final CriteriaQuery cq, final boolean isOffset) {
Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
getSession());
CriteriaImpl impl = (CriteriaImpl) criteria;
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
final int allCounts = ((Long) criteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
// 判断是否有排序字段
if (cq.getOrdermap() != null) {
cq.setOrder(cq.getOrdermap());
}
int pageSize = cq.getPageSize();// 每页显示数
int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
pageSize);// 当前页
int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
String toolBar = "";
if (isOffset) {// 是否分页
criteria.setFirstResult(offset);
criteria.setMaxResults(cq.getPageSize());
if (cq.getIsUseimage() == 1) {
toolBar = PagerUtil.getBar(cq.getMyAction(), cq.getMyForm(),
allCounts, curPageNO, pageSize, cq.getMap());
} else {
toolBar = PagerUtil.getBar(cq.getMyAction(), allCounts,
curPageNO, pageSize, cq.getMap());
}
} else {
pageSize = allCounts;
}
return new PageList(criteria.list(), toolBar, offset, curPageNO,
allCounts);
}
/**
* 返回JQUERY datatables DataTableReturn模型对象
*/
public DataTableReturn getDataTableReturn(final CriteriaQuery cq,
final boolean isOffset) {
Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
getSession());
CriteriaImpl impl = (CriteriaImpl) criteria;
// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
Projection projection = impl.getProjection();
final int allCounts = ((Long) criteria.setProjection(
Projections.rowCount()).uniqueResult()).intValue();
criteria.setProjection(projection);
if (projection == null) {
criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
}
// 判断是否有排序字段
if (cq.getOrdermap() != null) {
cq.setOrder(cq.getOrdermap());
}
int pageSize = cq.getPageSize();// 每页显示数
int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
pageSize);// 当前页
int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
if (isOffset) {// 是否分页
criteria.setFirstResult(offset);
criteria.setMaxResults(cq.getPageSize());
} else {
pageSize = allCounts;
}
//DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(), cq.getField().split(","), cq.getEntityClass(), false);
return new DataTableReturn(allCounts, allCounts, cq.getDataTables().getEcho(), criteria.list());
}
public EntityCriteria<T> setProjection(Projection projection) {
criteria.setProjection(projection);
return this;
}
public Projection getProjection() {
return projection;
}
private static LinkedHashMap<String, Projection> applyExpandDateModeCriterions(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
org.hibernate.criterion.Criterion or) {
// cartesian product <visitscheduleitems> x <start tag values> x <stop tag values>
org.hibernate.Criteria startTagValuesCriteria = visitScheduleItemCriteria.createCriteria("startTag", CriteriaSpecification.LEFT_JOIN)
.createCriteria("tagValues", "startTagValues", CriteriaSpecification.LEFT_JOIN);
org.hibernate.Criteria startTagValuesValueCriteria = startTagValuesCriteria.createCriteria("value",
CriteriaSpecification.LEFT_JOIN);
org.hibernate.Criteria stopTagValuesCriteria = visitScheduleItemCriteria.createCriteria("stopTag", CriteriaSpecification.LEFT_JOIN).createCriteria("tagValues",
"stopTagValues", CriteriaSpecification.LEFT_JOIN);
org.hibernate.Criteria stopTagValuesValueCriteria = stopTagValuesCriteria.createCriteria("value", CriteriaSpecification.LEFT_JOIN);
// from the cross product, remove those with start+stop values of different probands. also include rows without existing stop tag values
visitScheduleItemCriteria.add(CriteriaUtil.applyOr(
Restrictions.or(Restrictions.eqProperty("startTagValues.listEntry.id", "stopTagValues.listEntry.id"), Restrictions.isNull("stopTagValues.listEntry.id")), or));
// narrow to particular proband, if given
org.hibernate.Criteria startTagValuesListEntryCriteria = startTagValuesCriteria.createCriteria("listEntry", "startTagValuesListEntry", CriteriaSpecification.LEFT_JOIN);
if (probandId != null) {
startTagValuesListEntryCriteria.add(CriteriaUtil.applyOr(Restrictions.or(Restrictions.isNull("proband.id"), Restrictions.eq("proband.id", probandId.longValue())), or));
}
// only rows with proband group matching the group of the visitschelute item (or those with no group)
visitScheduleItemCriteria
.add(CriteriaUtil.applyOr(Restrictions.or(Restrictions.isNull("startTagValuesListEntry.id"),
Restrictions.or(Restrictions.eqProperty("startTagValuesListEntry.group.id", "group.id"), Restrictions.isNull("group.id"))), or));
CriteriaQueryTranslator translator = CriteriaUtil.getCriteriaQueryTranslator(visitScheduleItemCriteria);
// prepare sql fragments:
String offsetSql = translator.getColumn(visitScheduleItemCriteria, "offsetSeconds");
String durationSql = translator.getColumn(visitScheduleItemCriteria, "duration");
String tagStartSql = translator.getColumn(startTagValuesValueCriteria, "timestampValue");
String tagStopSql = translator.getColumn(stopTagValuesValueCriteria, "timestampValue");
String tagStartOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
tagStartSql, offsetSql);
String tagStopOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
tagStopSql, offsetSql);
String durationStopOffsetSql = MessageFormat.format(Settings.getString(SettingCodes.SQL_ADD_SECONDS_TERM, Bundle.SETTINGS, null),
tagStartOffsetSql, durationSql);
String probandIdSql = translator.getColumn(startTagValuesListEntryCriteria, "proband.id");
// date filtering
Junction junction = Restrictions.disjunction();
if (or != null) {
junction.add(or);
}
if (from != null || to != null) {
junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.STATIC), CriteriaUtil.getClosedIntervalCriterion(from, to, null)));
junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAGS),
Restrictions.and(Restrictions.sqlRestriction("(" + tagStartSql + ") < (" + tagStopSql + ")"),
CriteriaUtil.getClosedIntervalCriterion(from, to, null, tagStartOffsetSql, tagStopOffsetSql))));
junction.add(
Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAG_DURATION), Restrictions.and(Restrictions.sqlRestriction("(" + tagStartSql + ") is not null"),
CriteriaUtil.getClosedIntervalCriterion(from, to, null, tagStartOffsetSql, durationStopOffsetSql))));
visitScheduleItemCriteria.add(junction);
} else {
junction.add(Restrictions.eq("mode", VisitScheduleDateMode.STATIC));
junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAGS), Restrictions.sqlRestriction("(" + tagStartSql + ") < (" + tagStopSql + ")")));
junction.add(Restrictions.and(Restrictions.eq("mode", VisitScheduleDateMode.TAG_DURATION), Restrictions.sqlRestriction("(" + tagStartSql + ") is not null")));
}
visitScheduleItemCriteria.add(junction); //no stales any more
LinkedHashMap<String, Projection> sqlColumns = new LinkedHashMap<String, Projection>();
sqlColumns.put("tagStart", new SQLProjection(
tagStartOffsetSql + " as tagStart",
new String[] { "tagStart" },
new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
tagStartOffsetSql));
sqlColumns.put("tagStop", new SQLProjection(
tagStopOffsetSql + " as tagStop",
new String[] { "tagStop" },
new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
tagStopOffsetSql));
sqlColumns.put("durationStop", new SQLProjection(
durationStopOffsetSql + " as durationStop",
new String[] { "durationStop" },
new org.hibernate.type.Type[] { Hibernate.TIMESTAMP },
durationStopOffsetSql));
sqlColumns.put("probandId", new SQLProjection(
probandIdSql + " as probandId",
new String[] { "probandId" },
new org.hibernate.type.Type[] { Hibernate.LONG },
probandIdSql));
return sqlColumns;
}
public HibernateProjectionAdapter(Query.Projection projection) {
this.projection = projection;
}
public Projection toHibernateProjection() {
ProjectionAdapter projectionAdapter = adapterMap.get(projection.getClass());
if(projectionAdapter == null) throw new UnsupportedOperationException("Unsupported projection used: " + projection.getClass().getName());
return projectionAdapter.toHibernateProjection(projection);
}
public Projection getProjection() {
return projection;
}