@Override public Contrat getContratById(Long uidContrat) { final Criteria crit = createCriteria(Contrat.class); crit.add(Restrictions.eq("id", uidContrat)); crit.add(Restrictions.eq("isVisible", true)); return (Contrat) crit.uniqueResult(); }
/** * Tìm kiếm nhanh * * @param idHangDienThoai id của HangDienThoai. * @param ten tên DienThoai. * @param giaTu giá chặn dưới. * @param giaDen giá chặn trên. * @return Danh sách DienThoai thỏa tiêu chí tìm kiếm. */ @SuppressWarnings("unchecked") public List<DienThoai> quickSearch(int idHangDienThoai, String ten, double giaTu, double giaDen) { Session session = factory.getCurrentSession(); Criteria criteria = session.createCriteria(DienThoai.class); if (idHangDienThoai > 0) { Criterion manufacture = Restrictions.eq("hangDienThoai.id", idHangDienThoai); criteria.add(manufacture); } if (ten != null) { Criterion name = Restrictions.like("ten", "%" + ten + "%"); criteria.add(name); } if (giaTu >= 0.0) { Criterion minPrice = Restrictions.ge("giaHienHanh", giaTu); criteria.add(minPrice); } if (giaDen >= 0.0) { Criterion maxPrice = Restrictions.le("giaHienHanh", giaDen); criteria.add(maxPrice); } criteria.add(Restrictions.eq("xoa", false)); return criteria.list(); }
@Override public VerifyPO get(long uid, int type) { Criteria c = createCriteria(); c.add(Restrictions.eq("uid", uid)); c.add(Restrictions.eq("type", type)); return (VerifyPO) c.uniqueResult(); }
@SuppressWarnings("unchecked") public static java.util.List<Object> getListData( Class<?> classBean, String strKey1, Object value1, String strKey2, Object value2) { java.util.List<Object> result = new java.util.ArrayList<Object>(); Session session = null; try { session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); Criteria criteria = session.createCriteria(classBean); if (strKey1 != null) { criteria.add(Restrictions.like(strKey1, value1)); } if (strKey2 != null) { criteria.add(Restrictions.like(strKey2, value2)); } result = criteria.list(); tx.commit(); } finally { if (session != null) { session.close(); } } return result; }
private Criteria buildCriteria(QueryModel queryModel) { Criteria criteria = getCurrentSession().createCriteria(persistentClass); if (queryModel.getConditions() != null) { for (Condition condition : queryModel.getConditions()) { criteria.add((Criterion) condition.getConstraint()); } } for (Map.Entry<String, List<Condition>> associationCriteriaEntry : queryModel.getAssociationConditions().entrySet()) { Criteria associationCriteria = criteria.createCriteria(associationCriteriaEntry.getKey()); criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); for (Condition condition : associationCriteriaEntry.getValue()) { associationCriteria.add((Criterion) condition.getConstraint()); } } if (queryModel.getProjection() != null) { ProjectionList projectionList = Projections.projectionList(); projectionList.add( (org.hibernate.criterion.Projection) queryModel.getProjection().getDetails()); criteria.setProjection(projectionList); } return criteria; }
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; }
private void filtroPorStatus(Emprestimo filtro, Criteria criteria) { if (filtro.getOpFiltro() == 2) { criteria.add(Restrictions.isNull("c.dataDevolucao")); } else if (filtro.getOpFiltro() == 3) { criteria.add(Restrictions.isNotNull("c.dataDevolucao")); } }
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; }
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; }
@Override public Notice findById(int noticeId) throws OperationalException { Session session = null; Notice notice = null; try { session = parkingSessionFactory.getSessionFactory().openSession(); session.beginTransaction(); Criteria criteria = session.createCriteria(Notice.class); criteria.add(Restrictions.eq(NOTICEID, noticeId)); criteria.add(Restrictions.ne(STATUS, NoticeStatus.DELETED.name())); criteria.setMaxResults(1); notice = (Notice) criteria.uniqueResult(); return notice; } catch (Exception e) { LOGGER.error("findById: Exception ", e); throw new OperationalException( HttpConstants.INTERNAL_SERVER_ERROR, ResponseConstants.ERROR_FETCHING_FROM_DB, HttpStatus.INTERNAL_SERVER_ERROR); } finally { if (session != null) { session.close(); } } }
@Override public long standbyCount() throws OperationalException { Session session = null; long count = 0; try { session = parkingSessionFactory.getSessionFactory().openSession(); Criteria criteria = session.createCriteria(Notice.class); User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); String role = user.getRole(); criteria.add(Restrictions.eq("author", user)); criteria.add(Restrictions.ne(STATUS, NoticeStatus.DELETED.name())); criteria.setProjection(Projections.rowCount()); count = (long) criteria.uniqueResult(); } catch (Exception e) { LOGGER.error("unreadCount: error in unreadCount notfication", e); throw new OperationalException( HttpConstants.INTERNAL_SERVER_ERROR, ResponseConstants.ERROR_FETCHING_FROM_DB, HttpStatus.INTERNAL_SERVER_ERROR); } finally { if (session != null) { session.close(); } } return count; }
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<Lista> getByQuery(Map<String, Object> m) throws DataException { Criteria crit = this.getSession().createCriteria(Lista.class); /** Extraemos el mapa de parametros. */ Iterator it = m.entrySet().iterator(); while (it.hasNext()) { Map.Entry e = (Map.Entry) it.next(); if (e.getKey().equals("descripcion")) crit.add( Restrictions.sqlRestriction("trim(ucase(descripcion)) like '%" + e.getValue() + "%'")); if (e.getKey().equals("borrado")) crit.add(Restrictions.sqlRestriction("borrado=" + e.getValue())); if (e.getKey().equals("idUsuario")) crit.add(Restrictions.sqlRestriction("idUsuario=" + e.getValue())); } // reemplazar por la linea de arriba las dos siguientes si se requiere ordenacion // Si en vez de Criteria es un SQLQuery echa un vistazo a la clase del proyecto compras-rest // ProveedorMercanciaDAOImpl Criteria criteriaConOrder = asignarOrdenacionACriteria(crit); List<Lista> list = criteriaConOrder.list(); return list; }
/** * @param classBean * @param strKey * @param value * @return a first Object from a List of obejcts */ public static Object getObjectByKey( Class classBean, String strKey, String strKey2, Object value, Object value2, String strDbName) { Session session = getSessionDude(strDbName); // sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); List result = null; Object obj = null; try { Criteria criteria = session.createCriteria(classBean); if (strKey != null && strKey2 != null) { criteria.add(Restrictions.eq(strKey, value)); criteria.add(Restrictions.eq(strKey2, value2)); } result = criteria.list(); tx.commit(); if (result != null && result.size() > 0) { obj = result.get(0); } } finally { if (session != null && session.isOpen()) { session.close(); } } return obj; }
@Test @TestForIssue(jiraKey = "HHH-7767") public void testCriteriaRestrictionOnIdManyToOne() { Session s = openSession(); s.beginTransaction(); s.createQuery("from Course c join c.students cs join cs.student s where s.name = 'Foo'").list(); Criteria criteria = s.createCriteria(Course.class); criteria .createCriteria("students") .createCriteria("student") .add(Restrictions.eq("name", "Foo")); criteria.list(); Criteria criteria2 = s.createCriteria(Course.class); criteria2.createAlias("students", "cs"); criteria2.add(Restrictions.eq("cs.value", "Bar")); criteria2.createAlias("cs.student", "s"); criteria2.add(Restrictions.eq("s.name", "Foo")); criteria2.list(); s.getTransaction().commit(); s.close(); }
@Override public Long countParceirosInscritos( Integer idCursoSelecionado, Integer idGradeOficina, List<Integer> idsParceiros) { List<Integer> idsStatus = new ArrayList<Integer>(); idsStatus.add(Status.CANCELADO); idsStatus.add(Status.AGUARDANDO_VAGA_PRIORIDADE); idsStatus.add(Status.AGUARDANDO_VAGA); Criteria criteria = getSession().createCriteria(InscricaoGrade.class); criteria.createAlias("inscricaoCurso", "ic"); criteria.createAlias("ic.curso", "c"); criteria.add(Restrictions.eq("c.id", idCursoSelecionado)); criteria.createAlias("ic.ultimoStatus", "us"); criteria.createAlias("us.status", "s"); criteria.add(Restrictions.not(Restrictions.in("s.id", idsStatus))); criteria.createAlias("gradeOficina", "go"); criteria.add(Restrictions.eq("go.id", idGradeOficina)); if (idsParceiros != null && !idsParceiros.isEmpty()) { criteria.createAlias("ic.candidato", "cand"); criteria.add(Restrictions.in("cand.id", idsParceiros)); } criteria.setProjection(Projections.rowCount()); Long result = (Long) criteria.list().get(0); return result; }
public static List<LegalCustomer> searchLegalCustomer(LegalCustomer sentLegalCustomer) { Session session = HibernateUtil.getSession(); List<LegalCustomer> list = new ArrayList<>(); try { Transaction transaction = session.beginTransaction(); Criteria criteria = session.createCriteria(LegalCustomer.class); if (sentLegalCustomer.checkInfo()) { return null; } if (sentLegalCustomer.getID() != -1) { criteria.add(Restrictions.eq("ID", sentLegalCustomer.getID())); } if (!sentLegalCustomer.getEconomicID().equals("")) { criteria.add(Restrictions.eq("economicID", sentLegalCustomer.getEconomicID())); } if (!sentLegalCustomer.getName().equals("")) { criteria.add(Restrictions.eq("name", sentLegalCustomer.getName())); } list = criteria.list(); transaction.commit(); logger.info("User search for legal customers returned " + list.size() + "results."); return list; } catch (HibernateException ex) { ex.printStackTrace(); logger.error("User tried searching for legal customers. encountered error:", ex); return list; } finally { session.close(); } }
@Override public boolean duplicatecheck(String idProperty, Object id, Map<String, Object> map) { Criteria criteria = createCriteria(); if (map != null) { for (Iterator<String> i = map.keySet().iterator(); i.hasNext(); ) { String name = i.next(); if (filterProperty(name)) { criteria.add(Restrictions.eq(name, map.get(name))); } else { log.error("Could not resolve property:" + name); } } } if (null == id) { List<?> list = criteria.list(); if (list != null && list.size() > 0) { return true; } } else { List<?> list = criteria.add(Restrictions.ne(idProperty, id)).list(); if (list != null && list.size() > 0) { return true; } } return false; }
@SuppressWarnings("unchecked") @Override public List<PersonneStatut> rechercherStatutParCriteres(DimensionCriteresRechercheDto criteres) { final Criteria criteria = createCriteria(PersonneStatut.class); // Critère sur l'identifiant if (criteres.getId() != null) { criteria.add(Restrictions.eq("id", criteres.getId())); } // Critère sur le libelle if (criteres.getLibelle() != null && !criteres.getLibelle().equals("")) { criteria.add(Restrictions.ilike("libelle", criteres.getLibelle().toLowerCase() + "%")); } // Critère sur la visibilité if (criteres.getVisible() != null) { criteria.add(Restrictions.eq("visible", criteres.getVisible())); } // Maxresults if (criteres.getMaxResults() != null) { criteria.setFirstResult(0); criteria.setMaxResults(criteres.getMaxResults()); } // Ordonner les éléments criteria.addOrder(Order.asc("ordre")); criteria.addOrder(Order.asc("libelle")); return criteria.list(); }
/** * 查询一个对象的属性值在数据库中是不是唯一 * * @param entity 实体对象 * @param propertyNames 属性的名称,可多个 如:"prop1,prop2" * @return 针对 编辑 对象保存时 如果和其它 对象 属性名称相同 抛出异常问题 重写此方法 */ public boolean isUnique(Object entity, String propertyNames) { Class<?> clazz = getTrueClass(entity); Criteria criteria = createCriteria(clazz).setProjection(Projections.rowCount()); String[] nameList = propertyNames.split(","); try { boolean isQuery = false; for (String name : nameList) { Object obj = PropertyUtils.getProperty(entity, name); if (obj != null) { criteria.add(Restrictions.eq(name, obj)); isQuery = true; } else { isQuery = false; } } if (!isQuery) { return true; } String idName = getIdName(clazz); Serializable id = getId(clazz, entity); if (id != null) { criteria.add(Restrictions.not(Restrictions.eq(idName, id))); } } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } this.getSession().evict(entity); return (Integer) criteria.uniqueResult() == 0; }
@Override public List<ThesaurusConcept> getPaginatedAvailableConceptsOfGroup( Integer startIndex, Integer limit, String groupId, String thesaurusId, Boolean onlyValidatedConcepts, String like) { DetachedCriteria dc = DetachedCriteria.forClass(ThesaurusConceptGroup.class, "gr"); dc.createCriteria("concepts", "tc", JoinType.RIGHT_OUTER_JOIN); dc.setProjection(Projections.projectionList().add(Projections.property("tc.identifier"))); dc.add(Restrictions.eq("gr.identifier", groupId)); Criteria criteria = selectPaginatedConceptsByAlphabeticalOrder(startIndex, limit); criteria.add(Subqueries.propertyNotIn("tc.identifier", dc)); selectThesaurus(criteria, thesaurusId); criteria.add( Restrictions.not( Restrictions.and( Restrictions.eq("topConcept", false), Restrictions.or( Restrictions.isNull("tc.parentConcepts"), Restrictions.isEmpty("tc.parentConcepts"))))); if (null != like) { conceptNameIsLike(criteria, like); } onlyValidatedConcepts(criteria, onlyValidatedConcepts); return criteria.list(); }
public PagingWrapper<ChallengeChallengeReferral> getAllforChallengeReferralAndChallenge( final UUID challengeReferralId, final UUID challengeId, final SortingAndPaging sAndP) { final Criteria query = createCriteria(); query.add(Restrictions.eq("challengeReferral.id", challengeReferralId)); query.add(Restrictions.eq("challenge.id", challengeId)); return processCriteriaWithStatusSortingAndPaging(query, sAndP); }
/** * Adds an <code>Expression</code> to a <code>Criteria</code>. * * @param criteria * @param parameterName * @param parameterValue * @param comparatorID * @param matchMode */ private void addExpression( org.hibernate.Criteria criteria, String parameterName, Object parameterValue, int comparatorID, org.hibernate.criterion.MatchMode matchMode) { if (parameterValue != null) { switch (comparatorID) { case CriteriaSearchParameter.LIKE_COMPARATOR: { if ((matchMode != null) && (parameterValue instanceof String)) { criteria.add( org.hibernate.criterion.Expression.like( parameterName, (String) parameterValue, matchMode)); } else { criteria.add(org.hibernate.criterion.Expression.like(parameterName, parameterValue)); } break; } case CriteriaSearchParameter.INSENSITIVE_LIKE_COMPARATOR: { if ((matchMode != null) && (parameterValue instanceof String)) { criteria.add( org.hibernate.criterion.Expression.ilike( parameterName, (String) parameterValue, matchMode)); } else { criteria.add(org.hibernate.criterion.Expression.ilike(parameterName, parameterValue)); } break; } case CriteriaSearchParameter.EQUAL_COMPARATOR: { criteria.add(org.hibernate.criterion.Expression.eq(parameterName, parameterValue)); break; } case CriteriaSearchParameter.GREATER_THAN_OR_EQUAL_COMPARATOR: { criteria.add(org.hibernate.criterion.Expression.ge(parameterName, parameterValue)); break; } case CriteriaSearchParameter.GREATER_THAN_COMPARATOR: { criteria.add(org.hibernate.criterion.Expression.gt(parameterName, parameterValue)); break; } case CriteriaSearchParameter.LESS_THAN_OR_EQUAL_COMPARATOR: { criteria.add(org.hibernate.criterion.Expression.le(parameterName, parameterValue)); break; } case CriteriaSearchParameter.LESS_THAN_COMPARATOR: { criteria.add(org.hibernate.criterion.Expression.lt(parameterName, parameterValue)); break; } } } else { criteria.add(org.hibernate.criterion.Expression.isNull(parameterName)); } }
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 ArrayList<Election> getElectionByConstituency(Long constituency) { Session session = null; ArrayList<Election> eleclist = new ArrayList<Election>(); Criteria ctr, tempctr; try { session = getSessionFactory().openSession(); ctr = session.createCriteria(Locations.class); ctr.add(Restrictions.eq("constituency", constituency)); for (int i = 0; ctr.list().size() > 0 && i < ctr.list().size(); i++) { tempctr = session.createCriteria(Election.class); tempctr.add(Restrictions.eq("validity", Election.NOTDONE)); tempctr.add(Restrictions.idEq(((Locations) ctr.list().get(i)).getElecid())); tempctr.add(Restrictions.le("start", new Timestamp(new Date().getTime()))); tempctr.add(Restrictions.ge("end", new Timestamp(new Date().getTime()))); if (tempctr.list().size() > 0) eleclist.add((Election) tempctr.list().get(0)); } } catch (HibernateException e) { System.err.println("Error: file: LocationsDAO method: getNumOfCOnsti()"); } finally { if (session != null) session.close(); } return eleclist; }
public static Group findByOrgAndName(Organisation org, String name, Session session) { Criteria crit = session.createCriteria(Group.class); crit.setCacheable(true); crit.add(Restrictions.eq("organisation", org)); crit.add(Restrictions.eq("name", name)); return (Group) crit.uniqueResult(); }
public ArrayList<Candidate> getNumOfCandidateConstituency(Long constituency, String elecid) { Session session = null; ArrayList<String> numcon = new ArrayList<String>(); ArrayList<Candidate> numcan = new ArrayList<Candidate>(); Criteria ctr; try { session = getSessionFactory().openSession(); ctr = session.createCriteria(Locations.class); ctr.add(Restrictions.eq("elecid", elecid)); ctr.add(Restrictions.eq("constituency", constituency)); if (ctr.list().size() > 0) { ctr = session.createCriteria(Candidate.class); ctr.add(Restrictions.eq("constituency", constituency)); ctr.add(Restrictions.eq("validity", Candidate.ACCEPTED)); for (int i = 0; ctr.list().size() > 0 && i < ctr.list().size(); i++) numcan.add((Candidate) ctr.list().get(i)); } } catch (HibernateException e) { System.err.println("Error: file: LocationsDAO method: getNumOfCOnsti()"); } finally { if (session != null) session.close(); } return numcan; }
/** * Tìm kiếm nhanh * * @param c Tiêu chí tìm kiếm * @return Danh sách các điện thoại thỏa tiêu chí tìm kiếm */ @SuppressWarnings("unchecked") public List<DienThoai> quickSearch(QuickSearchCriteria c) { Session session = factory.getCurrentSession(); Criteria criteria = session.createCriteria(DienThoai.class); if (c.getIdHangDienThoai() > 0) { Criterion manufacture = Restrictions.eq("hangDienThoai.id", c.getIdHangDienThoai()); criteria.add(manufacture); } if (c.getTenDienThoai() != null) { Criterion name = Restrictions.like("ten", "%" + c.getTenDienThoai() + "%"); criteria.add(name); } if (c.getGiaTu() >= 0.0) { Criterion minPrice = Restrictions.ge("giaHienHanh", c.getGiaTu()); criteria.add(minPrice); } if (c.getGiaDen() >= 0.0) { Criterion maxPrice = Restrictions.le("giaHienHanh", c.getGiaDen()); criteria.add(maxPrice); } criteria.add(Restrictions.eq("xoa", false)); return criteria.list(); }
public List getChildPersons(String userId, boolean withSelfUser) { Criteria objCriteria = null; Session objSession = null; List objList = null; try { logger.info("GETTING ALL USERS"); objSession = HibernateUtil.getSession(); objCriteria = objSession.createCriteria(UsersVO.class).add(Restrictions.eq("valid", new Boolean(true))); if (withSelfUser) objCriteria.add( Restrictions.or( Restrictions.eq("userId", userId), Restrictions.eq("parentUser.userId", userId))); else objCriteria.add(Restrictions.eq("parentUser.userId", userId)); objCriteria.addOrder(Order.asc("userId")); objList = objCriteria.list(); logger.info("GET ALL USERS ENDS"); } catch (HibernateException e) { logger.error("HIBERNATE EXCEPTION DURING GET ALL USERS", e); e.printStackTrace(); } finally { if (objSession != null) { objSession.close(); } } return objList; }
@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(); }
@SuppressWarnings("unchecked") public List<T> find(Class<T> clazz, String title, int firstRow, int maxRow, String server) { /** &&短路符号 title.length()不会抛出异常(可省掉的) */ if (title != null && title.length() > 0) { /** 防止title=" "出现 */ title = title.replace(" ", ""); if (title.length() == 0) return null; } else { return null; } Criteria criteria = this.getSession().createCriteria(clazz); criteria.add( or( Restrictions.like("title", "%" + title + "%"), Restrictions.like("note", "%" + title + "%"))); criteria.addOrder(Order.asc("title")); if (null != server) { criteria.add(eq("server", server)); } /** 分页? 需要做一些优化 */ criteria.setFirstResult(firstRow); criteria.setMaxResults(maxRow); List<T> list = criteria.list(); return ((list == null) || list.isEmpty()) ? null : list; }