private Criteria getHBCriteria(Session session, SearchCriteria criteria) { Criteria newCriteria = session.createCriteria(WarrantyInformationType.class); if (criteria.getInternalId() != null) { newCriteria.add(Restrictions.eq("internalId", criteria.getInternalId())); } if ((criteria.ascending != null) && (criteria.ascending.contains("internalId"))) newCriteria.addOrder(Order.asc("internalId")); else if ((criteria.descending != null) && (criteria.descending.contains("internalId"))) newCriteria.addOrder(Order.desc("internalId")); if (criteria.getVersion() != null) { newCriteria.add(Restrictions.eq("version", criteria.getVersion())); } if ((criteria.ascending != null) && (criteria.ascending.contains("version"))) newCriteria.addOrder(Order.asc("version")); else if ((criteria.descending != null) && (criteria.descending.contains("version"))) newCriteria.addOrder(Order.desc("version")); if (criteria.getValue() != null) { newCriteria.add(Restrictions.eq("value", criteria.getValue())); } if ((criteria.ascending != null) && (criteria.ascending.contains("value"))) newCriteria.addOrder(Order.asc("value")); else if ((criteria.descending != null) && (criteria.descending.contains("value"))) newCriteria.addOrder(Order.desc("value")); if (criteria.getLanguageID() != null) { newCriteria.add(Restrictions.eq("languageID", criteria.getLanguageID())); } if ((criteria.ascending != null) && (criteria.ascending.contains("languageID"))) newCriteria.addOrder(Order.asc("languageID")); else if ((criteria.descending != null) && (criteria.descending.contains("languageID"))) newCriteria.addOrder(Order.desc("languageID")); return newCriteria; }
public Pager list(String username, int pageSize, int pageNo) { Session session = null; Pager pager = null; try { session = HibernateSessionFactory.currentSession(); Criteria criteria = session.createCriteria(Schedule.class); criteria.add(Restrictions.eq("username", username)); int rowCount = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue(); criteria.setProjection(null); int startIndex = pageSize * (pageNo - 1); criteria.addOrder(Order.desc("year")); criteria.addOrder(Order.desc("month")); criteria.addOrder(Order.desc("day")); criteria.setFirstResult(startIndex); criteria.setMaxResults(pageSize); List<?> result = criteria.list(); pager = new Pager(pageSize, pageNo, rowCount, result); } catch (HibernateException e) { pager = new Pager(pageSize, pageNo, 0, new ArrayList<Object>()); throw e; } finally { HibernateSessionFactory.closeSession(); } return pager; }
public Map<String, Object> lista(Map<String, Object> params) { log.debug("Buscando lista de facturas con params {}", params); if (params == null) { params = new HashMap<>(); } if (!params.containsKey("max")) { params.put("max", 10); } else { params.put("max", Math.min((Integer) params.get("max"), 100)); } if (params.containsKey("pagina")) { Long pagina = (Long) params.get("pagina"); Long offset = (pagina - 1) * (Integer) params.get("max"); params.put("offset", offset.intValue()); } if (!params.containsKey("offset")) { params.put("offset", 0); } Criteria criteria = currentSession().createCriteria(FacturaAlmacen.class); Criteria countCriteria = currentSession().createCriteria(FacturaAlmacen.class); if (params.containsKey("almacen")) { criteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen"))); countCriteria.createCriteria("almacen").add(Restrictions.idEq(params.get("almacen"))); } if (params.containsKey("filtro")) { String filtro = (String) params.get("filtro"); Disjunction propiedades = Restrictions.disjunction(); propiedades.add(Restrictions.ilike("folio", filtro, MatchMode.ANYWHERE)); criteria.add(propiedades); countCriteria.add(propiedades); } if (params.containsKey("order")) { String campo = (String) params.get("order"); if (params.get("sort").equals("desc")) { criteria.addOrder(Order.desc(campo)); } else { criteria.addOrder(Order.asc(campo)); } } else { criteria.createCriteria("estatus").addOrder(Order.asc("prioridad")); } criteria.addOrder(Order.desc("fechaModificacion")); if (!params.containsKey("reporte")) { criteria.setFirstResult((Integer) params.get("offset")); criteria.setMaxResults((Integer) params.get("max")); } params.put("facturas", criteria.list()); countCriteria.setProjection(Projections.rowCount()); params.put("cantidad", (Long) countCriteria.list().get(0)); return params; }
public List getAutoMobileList( int startLimit, int endLimit, AutomobileExpense autoMobile, String search_1st_order_by) { Session session = sessionFactory.openSession(); List list = new ArrayList(); try { Criteria criteria = createAutoMobileCriteria(session, autoMobile, ""); if (StringUtils.isNotBlank(search_1st_order_by)) { criteria.addOrder(Order.desc(search_1st_order_by)); } if (StringUtils.isBlank(search_1st_order_by)) { criteria.addOrder(Order.desc("automobileExpenseId")); } criteria.setFirstResult(startLimit); criteria.setMaxResults(endLimit); list = criteria.list(); } catch (HibernateException e) { e.printStackTrace(); } finally { session.close(); } return list; }
private Criteria getHBCriteria(Session session, SearchCriteria criteria) { Criteria newCriteria = session.createCriteria(LanguageCodeContentType.class); if (criteria.getInternalId() != null) { newCriteria.add(Restrictions.eq("internalId", criteria.getInternalId())); } if ((criteria.ascending != null) && (criteria.ascending.contains("internalId"))) newCriteria.addOrder(Order.asc("internalId")); else if ((criteria.descending != null) && (criteria.descending.contains("internalId"))) newCriteria.addOrder(Order.desc("internalId")); if (criteria.getVersion() != null) { newCriteria.add(Restrictions.eq("version", criteria.getVersion())); } if ((criteria.ascending != null) && (criteria.ascending.contains("version"))) newCriteria.addOrder(Order.asc("version")); else if ((criteria.descending != null) && (criteria.descending.contains("version"))) newCriteria.addOrder(Order.desc("version")); if (criteria.getLiteral() != null) { newCriteria.add(Restrictions.eq("literal", criteria.getLiteral())); } if ((criteria.ascending != null) && (criteria.ascending.contains("literal"))) newCriteria.addOrder(Order.asc("literal")); else if ((criteria.descending != null) && (criteria.descending.contains("literal"))) newCriteria.addOrder(Order.desc("literal")); if (criteria.getName() != null) { newCriteria.add(Restrictions.eq("name", criteria.getName())); } if ((criteria.ascending != null) && (criteria.ascending.contains("name"))) newCriteria.addOrder(Order.asc("name")); else if ((criteria.descending != null) && (criteria.descending.contains("name"))) newCriteria.addOrder(Order.desc("name")); return newCriteria; }
@Override public DetachedCriteria buildCriteria() { DetachedCriteria crit = DetachedCriteria.forClass(AccountCreditNote.class); if (isNotEmpty(filterModel.getSerial())) { crit.add(Restrictions.ilike("this.serial", filterModel.getSerial(), MatchMode.START)); } if (isNotEmpty(filterModel.getReference())) { crit.add(Restrictions.ilike("this.reference", filterModel.getReference(), MatchMode.START)); } if (isNotEmpty(filterModel.getCode())) { crit.add(Restrictions.ilike("this.code", filterModel.getCode(), MatchMode.START)); } if (filterModel.getBeginDate() != null) { crit.add(Restrictions.ge("this.date", filterModel.getBeginDate())); } if (filterModel.getEndDate() != null) { crit.add(Restrictions.le("this.date", filterModel.getEndDate())); } if (filterModel.getAccount() != null) { crit.add(Restrictions.le("this.account", filterModel.getAccount())); } crit.addOrder(Order.desc("serial")); crit.addOrder(Order.desc("date")); return crit; }
/** Add order directly to criteria. */ private static void addOrder(Criteria c, String sort, String order, boolean ignoreCase) { if (ORDER_DESC.equals(order)) { c.addOrder(ignoreCase ? Order.desc(sort).ignoreCase() : Order.desc(sort)); } else { c.addOrder(ignoreCase ? Order.asc(sort).ignoreCase() : Order.asc(sort)); } }
/* * (non-Javadoc) * * @see com.changpeng.common.action.AbstractAction#go() */ @Override protected String go() throws Exception { this.lawyer = this.getLoginUser(); // TODO Auto-generated method stub BasicService basic = (BasicService) getBean("basicService"); DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Articles.class); detachedCriteria.add(Restrictions.eq("type", type)); if (type == 1) { // 重要通知才搞这个。那个什么帮助就都显示了 // Criterion province = Restrictions.eq("provinceid", // this.getLoginUser().getProvinceid()); int directunion = this.getLoginUser().getDirectunion(); SysGroup group = (SysGroup) basic.get(SysGroup.class, directunion); detachedCriteria.add(Restrictions.eq("status", 0)); // 显示我的事务所的通知,显示我的律协的通知,显示我的省律协的通知,显示系统的通只 // detachedCriteria.add(Restrictions.in("thegroup", new Integer[] { // this.getLoginUser().getProvinceunion(), // this.getLoginUser().getDirectunion(), // this.getLoginUser().getTheoffice(), 0 })); Criterion province = Restrictions.in( "thegroup", new Integer[] { this.getLoginUser().getProvinceunion(), this.getLoginUser().getDirectunion(), this.getLoginUser().getTheoffice(), 0 }); Criterion c = Restrictions.eq("provinceid", 0); detachedCriteria.add(Restrictions.or(c, province)); detachedCriteria.addOrder(Order.desc("createtime")); } // 按现实顺序来 detachedCriteria.addOrder(Order.desc("listorder")); detachedCriteria.addOrder(Order.desc("createtime")); this.page = basic.findPageByCriteria(detachedCriteria, pageSize, pageNo); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); // 得到前一天 cal.add(Calendar.MONTH, -1); // 得到前一个月 long date = cal.getTimeInMillis(); System.out.println(date); // long lastdaya=df.format(new java.util.Date(date)); // System.out.println(lastdaya); lastday = new Timestamp(date); System.out.println(lastday); // TODO Auto-generated method stub return SUCCESS; }
public List<Roles> takeRoles() { List<Roles> lst = null; String sortType = null; try { Session session = getSession(); if (sort != null) { if (sort.indexOf('-') != -1) { sortType = "asc"; sort = sort.substring(1); } else { sortType = "desc"; } } Criteria cri = session.createCriteria(Roles.class); if (role != null) { if (role.getValue() != null && !"".equals(role.getValue())) { cri.add(Restrictions.eq("value", role.getValue())); } if (role.getName() != null && !"".equals(role.getName())) { cri.add(Restrictions.eq("name", role.getName())); } if (isactive != null) { cri.add(Restrictions.eq("isactive", "Y")); } else { cri.add(Restrictions.eq("isactive", "N")); } } if (sort != null) { if (sortType != null && sortType.equals("asc")) { cri.addOrder(Order.asc(sort).ignoreCase()); } else if (sortType != null && sortType.equals("desc")) { cri.addOrder(Order.desc(sort).ignoreCase()); } } else { cri.addOrder(Order.desc("lastUpdate").ignoreCase()); } if (startval >= 0) { cri.setFirstResult(startval); } if (count >= 0) { cri.setMaxResults(count); } lst = cri.list(); } catch (Exception ex) { ex.printStackTrace(); } return lst; }
@Override protected List<Order> getOrder(SortParam sort) { if (sort.getProperty() == null || !sort.getProperty().equals("priority")) { return super.getOrder(sort); } if (sort.isAscending()) { return Arrays.asList(Order.asc("priority"), Order.asc("type")); } else { return Arrays.asList(Order.desc("priority"), Order.desc("type")); } }
public Pager findPager(Pager pager, Criteria criteria) { Assert.notNull(pager, "pager is required"); Assert.notNull(criteria, "criteria is required"); Integer pageNumber = pager.getPageNumber(); Integer pageSize = pager.getPageSize(); String searchBy = pager.getSearchBy(); String keyword = pager.getKeyword(); String orderBy = pager.getOrderBy(); Pager.Order order = pager.getOrder(); if (StringUtils.isNotEmpty(searchBy) && StringUtils.isNotEmpty(keyword)) { if (searchBy.contains(".")) { String alias = StringUtils.substringBefore(searchBy, "."); criteria.createAlias(alias, alias); } criteria.add(Restrictions.like(searchBy, "%" + keyword + "%")); } pager.setTotalCount(criteriaResultTotalCount(criteria)); if (StringUtils.isNotEmpty(orderBy) && order != null) { if (order == Pager.Order.asc) { criteria.addOrder(Order.asc(orderBy)); } else { criteria.addOrder(Order.desc(orderBy)); } } ClassMetadata classMetadata = sessionFactory.getClassMetadata(entityClass); if (!StringUtils.equals(orderBy, ORDER_LIST_PROPERTY_NAME) && ArrayUtils.contains(classMetadata.getPropertyNames(), ORDER_LIST_PROPERTY_NAME)) { criteria.addOrder(Order.asc(ORDER_LIST_PROPERTY_NAME)); criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME)); if (StringUtils.isEmpty(orderBy) || order == null) { pager.setOrderBy(ORDER_LIST_PROPERTY_NAME); pager.setOrder(Pager.Order.asc); } } else if (!StringUtils.equals(orderBy, CREATE_DATE_PROPERTY_NAME) && ArrayUtils.contains(classMetadata.getPropertyNames(), CREATE_DATE_PROPERTY_NAME)) { criteria.addOrder(Order.desc(CREATE_DATE_PROPERTY_NAME)); if (StringUtils.isEmpty(orderBy) || order == null) { pager.setOrderBy(CREATE_DATE_PROPERTY_NAME); pager.setOrder(Pager.Order.desc); } } criteria.setFirstResult((pageNumber - 1) * pageSize); criteria.setMaxResults(pageSize); pager.setResult(criteria.list()); return pager; }
/** 功能:读取分页数据 */ public PageResult readAllPages(int pageSize, int currentPage, SearchFilter filter) { try { DetachedCriteria detachedCriteria = DetachedCriteria.forClass(PhotosCover.class); detachedCriteria.add(Restrictions.eq("status", EntityStatus.NORMAL)); detachedCriteria.addOrder(Order.desc("defaults")); detachedCriteria.addOrder(Order.desc("createDT")); DetachedCriteriaUtil.addSearchFilter(detachedCriteria, filter); return baseDAO.findByPages(detachedCriteria, pageSize, currentPage); } catch (Exception ex) { ex.printStackTrace(); throw new BaseException("查询所有分页异常"); } }
/** * The 'findConfigurations' function will return a list of configurations based on a search term * passed in. The function will search configurations on the following fields configName, orgName * and messageTypeName @Table configurations * * @param searchTerm Will hold the term used search configurations on * @return This function will return a list of configuration objects */ @Override @SuppressWarnings("unchecked") public List<configuration> findConfigurations(String searchTerm) { if (searchTerm != "") { // get a list of organization id's that match the term passed in List<Integer> orgIdList = new ArrayList<Integer>(); Criteria findOrgs = sessionFactory.getCurrentSession().createCriteria(Organization.class); findOrgs.add(Restrictions.like("orgName", "%" + searchTerm + "%")); List<Organization> orgs = findOrgs.list(); for (Organization org : orgs) { orgIdList.add(org.getId()); } // get a list of message type id's that match the term passed in List<Integer> msgTypeIdList = new ArrayList<Integer>(); Criteria findMsgTypes = sessionFactory.getCurrentSession().createCriteria(messageType.class); findMsgTypes.add(Restrictions.like("name", "%" + searchTerm + "%")); List<messageType> msgTypes = findMsgTypes.list(); for (messageType msgType : msgTypes) { msgTypeIdList.add(msgType.getId()); } Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class); if (orgIdList.size() == 0) { orgIdList.add(0); } if (msgTypeIdList.size() == 0) { msgTypeIdList.add(0); } criteria .add( Restrictions.or( Restrictions.in("orgId", orgIdList), Restrictions.in("messageTypeId", msgTypeIdList))) .addOrder(Order.desc("dateCreated")); return criteria.list(); } else { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(configuration.class); criteria.addOrder(Order.desc("dateCreated")); return criteria.list(); } }
@Override public <T extends GettableById> List<T> get( Class<T> bookEntityClass, int from, int to, Map<String, List<Criterion>> restrictions, OrderByFilter filter) { validateTransaction(); Criteria criteria = getSession().createCriteria(bookEntityClass); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); criteria.setFirstResult(from); if (to != 0) criteria.setMaxResults(to); for (String key : restrictions.keySet()) { if (key.equals(RestrictionsFields.MAIN_RESTRICTIONS)) { for (Criterion restriction : restrictions.get(RestrictionsFields.MAIN_RESTRICTIONS)) criteria.add(restriction); } else if (restrictions.get(key).size() > 0) { Criteria c = criteria.createCriteria(key); for (Criterion restriction : restrictions.get(key)) c.add(restriction); } } if (filter != null) { if (filter.getDirection().equals(OrderByFilter.ASC)) criteria.addOrder(Order.asc(filter.field)); else criteria.addOrder(Order.desc(filter.field)); } return criteria.list(); }
private void buildOrderClause( StringBuilder queryStringBuilder, QueryModel queryModel, Criteria criteria, CriteriaQueryTranslator criteriaQueryTranslator) { boolean firstOrderItem = true; if (queryModel.getSorts() != null) { for (Sort sort : queryModel.getSorts()) { if (firstOrderItem) { queryStringBuilder.append(" order by "); } else { queryStringBuilder.append(','); } Order order = sort.getSortDirection() == SortDirection.Ascending ? Order.asc(sort.getField()) : Order.desc(sort.getField()); queryStringBuilder.append(order.toSqlString(criteria, criteriaQueryTranslator)); firstOrderItem = false; } } }
@Override public Iterable<T> findUsingQueryModel(QueryModel queryModel) { if (accessControlContextProvider == null || roleAllowsAccess(queryModel.getAccessControlContext().getRole())) { Criteria criteria = buildCriteria(queryModel); if (queryModel.getSorts() != null) { for (Sort sort : queryModel.getSorts()) { criteria.addOrder( sort.getSortDirection() == SortDirection.Ascending ? Order.asc(sort.getField()) : Order.desc(sort.getField())); } } if (queryModel.getMaxResults() > 0) { criteria.setMaxResults(queryModel.getMaxResults()); } if (queryModel.getFirstResult() > 0) { criteria.setFirstResult(queryModel.getFirstResult()); } //noinspection unchecked return criteria.list(); } else { //noinspection unchecked return createEntryBasedQuery(queryModel).list(); } }
@SuppressWarnings("unchecked") public List<Token> findTokens( Token search, int first, int pageSize, String sortField, SortOrder sortOrder) throws DAOException { List<Token> results = null; Session session = null; try { session = getSession(); Criteria criteria = criteria(session, search); criteria.setFirstResult(first); criteria.setMaxResults(pageSize); if (sortField == null) { sortField = "tokenId"; } Order ord = (sortOrder == null || sortOrder.equals(SortOrder.UNSORTED) || sortOrder.equals(SortOrder.ASCENDING)) ? Order.asc(sortField) : Order.desc(sortField); criteria.addOrder(ord); results = criteria.list(); } catch (Exception e) { throw new DAOException(e); } finally { if (session != null) { session.close(); } } return results; }
/** * Adiciona ordenação a uma criteria. * * @param propriedade Propriedade utilizada na ordenação. * @param ascendente true caso ascendente, false caso descendente. * @param criteria Criteria na qual a ordenação será adicionada. */ protected void adicionarOrdenacao(String propriedade, boolean ascendente, Criteria criteria) { if (ascendente) { criteria.addOrder(Order.asc(propriedade).ignoreCase()); } else { criteria.addOrder(Order.desc(propriedade).ignoreCase()); } }
private Criteria createCriteriaExactly( final Enterprise enterprise, final String filter, final String orderBy, final boolean desc, final boolean discardNullEnterprises) { Criteria criteria = createCriteria(); if (enterprise != null) { if (discardNullEnterprises) { criteria.add(sameEnterprise(enterprise)); } else { criteria.add(sameEnterpriseOrNull(enterprise)); } } else { criteria.add(genericRole()); } if (!StringUtils.isEmpty(filter)) { criteria.add(filterExactlyBy(filter)); } if (!StringUtils.isEmpty(orderBy)) { Order order = Order.asc(orderBy); if (desc) { order = Order.desc(orderBy); } criteria.addOrder(order); criteria.addOrder(Order.asc(Role.NAME_PROPERTY)); } return criteria; }
@SuppressWarnings("unchecked") @Override public List<Sales> getPendingSalesBetween(Date startDate, Date endDate) throws Exception { Session session = HibernateUtil.startSession(); Criteria criteria = session.createCriteria(Sales.class); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); List<Sales> sales = new ArrayList<Sales>(); try { Date lowerBound = DateTool.getTomorrowDate(DateTool.getDateWithoutTime(startDate)); Date upperBound = DateTool.getDateWithoutTime(endDate); sales = criteria .add(Restrictions.ge("date", lowerBound)) .add(Restrictions.lt("date", upperBound)) .add(Restrictions.eq("valid", true)) .add(Restrictions.isNull("inventorySheetData")) .addOrder(Order.desc("date")) .list(); } catch (HibernateException ex) { ex.printStackTrace(); } finally { session.close(); } return sales; }
/** * bar info query * * @param global * @return * @throws JSONException */ public String queryBarInfo(String global) throws JSONException { DetachedCriteria dc = DetachedCriteria.forClass(TNavigation.class); dc.add(Restrictions.eq("status", 1)); dc.addOrder(Order.asc("ordinal")).addOrder(Order.desc("updatetime")); List<TNavigation> list = super.findByDetachedCriteria(dc); List<TBar> rootList = new ArrayList<TBar>(); for (TNavigation navtion : list) { if ("0".equals(navtion.getObjid())) { TBar bar = new TBar(); bar.setName(ActionUtils.getLanStr(navtion.getName(), navtion.getEname(), global)); bar.setId(navtion.getOid()); bar.setObjid(navtion.getObjid()); rootList.add(bar); } } TNavigation record = new TNavigation(); record.getBarList().add(rootList); record = this.convertBar(record, rootList, list, global); // JSONArray itms = (JSONArray) JSONSerializer.toJSON(record.getBarList()); // return itms.toString(); return JSONUtil.serialize(record.getBarList(), null, null, false, false, true); }
/** 创建Criteria对象,带排序字段与升降序字段. */ public Criteria createCriteria(String orderBy, boolean isAsc, Criterion... criterions) { Assert.hasText(orderBy); Criteria criteria = createCriteria(criterions); if (isAsc) criteria.addOrder(Order.asc(orderBy)); else criteria.addOrder(Order.desc(orderBy)); return criteria; }
@SuppressWarnings("unchecked") @Override public List<Firma> getAll() { Criteria criteria = getSession().createCriteria(Firma.class); criteria.addOrder(Order.desc("id")); return (List<Firma>) criteria.list(); }
public Page<Log> find(Page<Log> page, Map<String, Object> paramMap) { DetachedCriteria dc = logDao.createDetachedCriteria(); Long createById = StringUtils.toLong(paramMap.get("createById")); if (createById > 0) { dc.add(Restrictions.eq("createBy.id", createById)); } String requestUri = ObjectUtils.toString(paramMap.get("requestUri")); if (StringUtils.isNotBlank(requestUri)) { dc.add(Restrictions.like("requestUri", "%" + requestUri + "%")); } String exception = ObjectUtils.toString(paramMap.get("exception")); if (StringUtils.isNotBlank(exception)) { dc.add(Restrictions.eq("type", Log.TYPE_EXCEPTION)); } Date beginDate = DateUtils.parseDate(paramMap.get("beginDate")); if (beginDate == null) { beginDate = DateUtils.setDays(new Date(), 1); paramMap.put("beginDate", DateUtils.formatDate(beginDate, "yyyy-MM-dd")); } Date endDate = DateUtils.parseDate(paramMap.get("endDate")); if (endDate == null) { endDate = DateUtils.addDays(DateUtils.addMonths(beginDate, 1), -1); paramMap.put("endDate", DateUtils.formatDate(endDate, "yyyy-MM-dd")); } dc.add(Restrictions.between("createDate", beginDate, endDate)); dc.addOrder(Order.desc("id")); return logDao.find(page, dc); }
@SuppressWarnings("unchecked") public static void main(String[] args) { SessionFactory factory = null; Session session = null; org.hibernate.Transaction tx = null; try { factory = HibernateUtil.getSessionFactory(); session = factory.openSession(); tx = session.beginTransaction(); List<Transaction> transactions = session.createCriteria(Transaction.class).addOrder(Order.desc("title")).list(); for (Transaction t : transactions) { System.out.println(t.getTitle()); } tx.commit(); } catch (Exception e) { e.printStackTrace(); tx.rollback(); } finally { session.close(); factory.close(); } }
/** * 使用检索标准对象分页查询 * * @param detachedCriteria * @param page * @return */ @SuppressWarnings("unchecked") public Page<T> find(Page<T> page, DetachedCriteria detachedCriteria) { // get count if (!page.isDisabled() && !page.isNotCount()) { page.setCount(count(detachedCriteria)); if (page.getCount() < 1) { return page; } } Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); criteria.setResultTransformer(Criteria.ROOT_ENTITY); // set page if (!page.isDisabled()) { criteria.setFirstResult(page.getFirstResult()); criteria.setMaxResults(page.getMaxResults()); } // order by if (StringUtils.isNotBlank(page.getOrderBy())) { for (String order : StringUtils.split(page.getOrderBy(), ",")) { String[] o = StringUtils.split(order, " "); if (o.length >= 1) { criteria.addOrder(Order.asc(o[0])); } else if (o.length >= 2) { if ("DESC".equals(o[1].toUpperCase())) { criteria.addOrder(Order.desc(o[0])); } else { criteria.addOrder(Order.asc(o[0])); } } } } page.setList(criteria.list()); return page; }
@Override public Long getTotal(CommentBo bo) { Criteria criteria = createRowCountsCriteria(Comment.class); initCriteria(criteria, bo); criteria.addOrder(Order.desc("createdDatetime")); return (Long) criteria.uniqueResult(); }
@Override public List<ReadingEnergy> getList() { @SuppressWarnings("unchecked") List<ReadingEnergy> list = getSession().createCriteria(ReadingEnergy.class).addOrder(Order.desc("readingDate")).list(); return list; }
public EnhancedRule setRule(EnhancedRule rule, BlogCommentQuery query) { if (query != null) { if (query.name != null) { rule.add(Restrictions.like("name", query.name, MatchMode.ANYWHERE)); } if (query.content != null) { rule.add(Restrictions.like("content", query.content, MatchMode.ANYWHERE)); } if (query.email != null) { rule.add(Restrictions.like("email", query.email, MatchMode.ANYWHERE)); } if (query.im != null) { rule.add(Restrictions.like("im", query.im, MatchMode.ANYWHERE)); } if (query.ip != null) { rule.add(Restrictions.like("ip", query.ip, MatchMode.ANYWHERE)); } if (query.website != null) { rule.add(Restrictions.like("website", query.website, MatchMode.ANYWHERE)); } if (query.userId != null) { rule.add(Restrictions.eq("user.id", query.userId)); } if (query.blogId != null) { rule.add(Restrictions.eq("blog.id", query.blogId)); } if (query.getOrder() != null) { rule.addOrder(query.getDesc() ? Order.desc(query.getOrder()) : Order.asc(query.getOrder())); } } return rule; }
/** * prepare query based on criteria * * @param session hib session * @return the query */ private Criteria attachCriteriaInfo(Session session) { Criteria query = null; if (StringUtils.isBlank(this.entityName)) { if (StringUtils.isBlank(this.alias)) { query = session.createCriteria(this.persistentClass); } else { query = session.createCriteria(this.persistentClass, alias); } } else { query = session.createCriteria(this.entityName); } // add criterions if (this.criterions != null) { query.add(this.criterions); } boolean secondLevelCaching = HibUtils.secondLevelCaching( ByCriteriaStatic.this.cacheable, ByCriteriaStatic.this.queryOptions); query.setCacheable(secondLevelCaching); if (secondLevelCaching) { String secondLevelCacheRegion = HibUtils.secondLevelCacheRegion( ByCriteriaStatic.this.cacheRegion, ByCriteriaStatic.this.queryOptions); if (!StringUtils.isBlank(secondLevelCacheRegion)) { query.setCacheRegion(secondLevelCacheRegion); } } QuerySort querySort = this.queryOptions == null ? null : this.queryOptions.getQuerySort(); if (querySort != null) { List<QuerySortField> sorts = querySort.getQuerySortFields(); for (QuerySortField theSort : GrouperUtil.nonNull(sorts)) { Order order = theSort.isAscending() ? Order.asc(theSort.getColumn()) : Order.desc(theSort.getColumn()); query.addOrder(order); } } QueryPaging queryPaging = this.queryOptions == null ? null : this.queryOptions.getQueryPaging(); if (queryPaging != null) { // GRP-1024: sql server problems with paging page number when not initted if (queryPaging.getFirstIndexOnPage() < 0) { query.setFirstResult(0); } else { query.setFirstResult(queryPaging.getFirstIndexOnPage()); } query.setMaxResults(queryPaging.getPageSize()); } return query; }