List of usage examples for org.hibernate Criteria setProjection
public Criteria setProjection(Projection projection);
From source file:cn.newtouch.util.hibernate.HibernateDao.java
License:Apache License
/** * countCriteria./*w w w. ja va2 s .co m*/ */ @SuppressWarnings("unchecked") protected long countCriteriaResult(final Criteria c) { CriteriaImpl impl = (CriteriaImpl) c; // Projection?ResultTransformer?OrderBy??,??Count? Projection projection = impl.getProjection(); ResultTransformer transformer = impl.getResultTransformer(); List<CriteriaImpl.OrderEntry> orderEntries = null; try { orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries"); ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList()); } catch (Exception e) { logger.error("??:{}", e.getMessage()); } // Count Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult(); long totalCount = (totalCountObject != null) ? totalCountObject : 0; // ?Projection,ResultTransformerOrderBy?? c.setProjection(projection); if (projection == null) { c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } if (transformer != null) { c.setResultTransformer(transformer); } try { ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries); } catch (Exception e) { logger.error("??:{}", e.getMessage()); } return totalCount; }
From source file:cn.trymore.core.dao.impl.DAOGenericImpl.java
License:Open Source License
@SuppressWarnings("unchecked") public PaginationSupport<T> findPageByCriteria(final DetachedCriteria criteria, final int pageSize, final int startIndex, final boolean dataFilter) throws DAOException { if (dataFilter && UtilString.isNotEmpty(this.getQueryFilter())) { criteria.add(Restrictions.sqlRestriction(this.getQueryFilter())); this.setQueryFilter(null); }//from w w w . jav a 2 s . c o m return (PaginationSupport<T>) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Criteria execCriteria = criteria.getExecutableCriteria(session); int rowCount = ((Integer) execCriteria.setProjection(Projections.rowCount()).uniqueResult()) .intValue(); execCriteria.setProjection(null); execCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); //execCriteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); execCriteria.setFirstResult(startIndex); if (pageSize > 0) { execCriteria.setMaxResults(pageSize); } else { execCriteria.setMaxResults(rowCount); } List<T> items = execCriteria.list(); return rowCount > 0 ? new PaginationSupport<T>(items, rowCount, startIndex, pageSize > 0 ? pageSize : rowCount) : null; } }); }
From source file:co.com.codesoftware.logic.ProductoLogic.java
/** * Funcion que consulta el count de la tabla de productos * * @return//from w w w. ja v a 2s. c om */ public Integer consultaCount() { Criteria crit = sesion.createCriteria(ProductoEntity.class); crit.setProjection(Projections.max("id")); Integer count = (Integer) crit.uniqueResult() + 1; return count; }
From source file:co.com.codesoftware.logic.ProductoTmpLogic.java
/** * Funcion para consultar el maximo de una tabla * * @return/*from ww w.j a v a 2s . c om*/ */ public Integer consultaMax() { Criteria crit = sesion.createCriteria(ProductoTmpEntity.class); crit.setProjection(Projections.max("id")); Integer count = 1; try { count = (Integer) crit.uniqueResult() + 1; } catch (Exception e) { count = 1; } return count; }
From source file:co.com.codesoftware.logica.facturacion.FacturacionLogica.java
/** * Funcion con la cual obtengo el valor de * * @param valor/*w w w . j a v a 2 s . c om*/ * @return */ public BigDecimal obtieneValorFacturasMes(Integer valor) { BigDecimal valorTotal = null; System.out.println("Valor " + valor); try { this.initOperation(); Criteria crit = this.sesion.createCriteria(FacturaEntity.class); crit.setProjection(Projections.sum("valor")); if (valor == 0) { crit.add(Restrictions .sqlRestriction("to_char(fact_fec_ini , 'mm/yyyy') = to_char(now(), 'mm/yyyy')")); } else { crit.add(Restrictions .sqlRestriction("to_char(fact_fec_ini , 'mm/yyyy') = to_char(current_date + interval '-" + valor + " month', 'mm/yyyy')")); } valorTotal = (BigDecimal) crit.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return valorTotal; }
From source file:co.com.siscomputo.administracion.logic.UsuarioLogic.java
/** * * @param idGrupo//from w w w. j ava 2 s .c o m * @return */ public ObjetoRetornaEntity listaUsuariosPorGrupo(int idGrupo) { ObjetoRetornaEntity retorna = new ObjetoRetornaEntity(); try { String validaConexion = initOperation(); if (!"Ok".equalsIgnoreCase(validaConexion)) { } else { //System.out.println("id GRupo: "+idGrupo); Criteria criteria = sesion.createCriteria(UsuarioGrupoUsuarioEntity.class) .add(Restrictions.eq("grupoUsuario.idGrupoUsuarios", idGrupo)); criteria.setProjection(Projections.groupProperty("usuario")); retorna.setRetorna((ArrayList<Object>) criteria.list()); retorna.setNumeroRespuesta(100); retorna.setTrazaRespuesta("Carga de usuario Por grupo"); } } catch (Exception e) { retorna.setNumeroRespuesta(3); retorna.setTrazaRespuesta("ERROR: " + e); e.printStackTrace(); } finally { try { //sesion.close(); sesion.close(); } catch (HibernateException hibernateException) { hibernateException.printStackTrace(); } } return retorna; }
From source file:co.id.pegadaian.pasg2.util.SusunTree.java
public Set<BigDecimal> listMenuByUser(Session session, String userId) { /* Ambil gropu by user */ Criteria critGroup = session.createCriteria(TblUserGroup.class); critGroup.add(Restrictions.eq("id.userId", userId)); critGroup.setProjection(Projections.projectionList().add(Projections.property("id.groupId")));//"id.groupId" List<BigDecimal> l = critGroup.list(); if (l.size() > 0) { // for(BigDecimal x :l){System.out.println(x); } /*Menu berdasarkan Priviledge */ Criteria c = session.createCriteria(TblPriviledge.class); c.add(Restrictions.in("id.groupId", l)); c.setProjection(Projections.projectionList().add(Projections.property("id.menuId"))); Set<BigDecimal> lMenuId = new HashSet(); List<BigDecimal> k = c.list(); for (BigDecimal x : k) { lMenuId.add(x);//new BigDecimal(x)); // System.out.println(x.getid().getMenuId()); // System.out.println(k); }/*from ww w . j ava 2 s . c o m*/ return lMenuId; } else { return null; } }
From source file:co.id.pegadaian.pasg2.util.SusunTreeJeasyUI.java
public Set<BigDecimal> listMenuByUser(Session session, String userId) { /* Ambil gropu by user */ Criteria critGroup = session.createCriteria(TblUserGroup.class); critGroup.add(Restrictions.eq("id.userId", userId)); critGroup.setProjection(Projections.projectionList().add(Projections.property("id.groupId")));//"id.groupId" List<BigDecimal> l = critGroup.list(); if (l.size() > 0) { /*Menu berdasarkan Priviledge */ Criteria c = session.createCriteria(TblPriviledge.class); c.add(Restrictions.in("id.groupId", l)); c.setProjection(Projections.projectionList().add(Projections.property("id.menuId"))); Set<BigDecimal> lMenuId = new HashSet(); List<BigDecimal> k = c.list(); for (BigDecimal x : k) { lMenuId.add(x);//new BigDecimal(x)); }//from ww w.j a v a 2 s . co m return lMenuId; } else { return null; } }
From source file:co.webmonkey.models.management.WebsiteManagement.java
public boolean isInstalled() { session.getTransaction().begin();/*from ww w . j a v a 2 s . c o m*/ Criteria cr = session.createCriteria(Users.class); cr.setProjection(Projections.rowCount()); int nb = ((Long) cr.uniqueResult()).intValue(); session.getTransaction().commit(); return nb > 0; }
From source file:com.abiquo.abiserver.commands.UserCommand.java
License:Mozilla Public License
/** * Returns a list of users stored in the Data Base * //from w w w.j ava2s .co m * @param userSession * @param userListOptions an UserListOptions object containing the options to retrieve the list * of users * @return A DataResult object containing an UserListResult object with an ArrayList of User and * the number of total users */ @SuppressWarnings("unchecked") protected DataResult<UserListResult> getUsers(UserSession userSession, UserListOptions userListOptions) { DataResult<UserListResult> dataResult = new DataResult<UserListResult>(); UserListResult userListResult = new UserListResult(); Session session = null; Transaction transaction = null; try { session = HibernateUtil.getSession(); transaction = session.beginTransaction(); // Getting the user that called this method UserHB userHB = (UserHB) session.createCriteria(UserHB.class) .add(Restrictions.eq("user", userSession.getUser())).uniqueResult(); // getUsers has two different authorization resources // If the user who called this method, does not match the security level for the // authorization resource // USER_GET_ALL_USERS, this method will only return those users who belongs to the same // enterprise than // the user that called this method // Getting the authorization resource USER_GET_ALL_USERS AuthResourceHB authResourceHB = (AuthResourceHB) session.createCriteria(AuthResourceHB.class) .add(Restrictions.eq("name", "USER_GET_ALL_USERS")).uniqueResult(); // Checking if the user has not the necessary security level to see the whole list of // Users. If so, we force // the userListOptions object to filter by the enterprise assigned to the user if (authResourceHB.getRoleHB().getSecurityLevel() .compareTo(userHB.getRoleHB().getSecurityLevel()) == -1) { // NOT GRANTED! userListOptions.setByEnterprise((Enterprise) userHB.getEnterpriseHB().toPojo()); } // Creating users criteria Criteria usersListCriteria = session.createCriteria(UserHB.class); Criteria usersCountCriteria = session.createCriteria(UserHB.class); // Removing the users that are deleted usersListCriteria.add(Restrictions.eq("deleted", 0)); usersCountCriteria.add(Restrictions.eq("deleted", 0)); // Adding filter by name, surname or email Disjunction filterDisjunction = Restrictions.disjunction(); if (userListOptions.getFilter().length() > 0) { filterDisjunction.add(Restrictions.like("name", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("surname", '%' + userListOptions.getFilter() + '%')); filterDisjunction.add(Restrictions.like("email", '%' + userListOptions.getFilter() + '%')); } usersListCriteria.add(filterDisjunction); usersCountCriteria.add(filterDisjunction); // Adding filter by Enterprise if (userListOptions.getByEnterprise() != null) { usersListCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); usersCountCriteria.add(Restrictions.eq("enterpriseHB", (EnterpriseHB) userListOptions.getByEnterprise().toPojoHB())); } // Adding order // Little fix to match the object used in Hibernate if (userListOptions.getOrderBy().compareTo("role") == 0) userListOptions.setOrderBy("roleHB"); Order order; if (userListOptions.getAsc()) order = Order.asc(userListOptions.getOrderBy()); else order = Order.desc(userListOptions.getOrderBy()); usersListCriteria.addOrder(order); usersCountCriteria.addOrder(order); // Adding filter to get only the users that currently have an active session if (userListOptions.getLoggedOnly()) { ArrayList<String> currentLoggedUsers = (ArrayList<String>) session .createSQLQuery("SELECT user FROM session WHERE expireDate > CURRENT_TIMESTAMP()").list(); usersListCriteria.add(Restrictions.in("user", currentLoggedUsers)); usersCountCriteria.add(Restrictions.in("user", currentLoggedUsers)); } // Once we have the criteria... // 1. Getting the total number of users that match userListOptions Integer totalUsers = (Integer) usersCountCriteria.setProjection(Projections.rowCount()).uniqueResult(); // 2. Getting the list of users, applying an offset and a max of results ArrayList<UserHB> usersHB = (ArrayList<UserHB>) usersListCriteria .setFirstResult(userListOptions.getOffset()).setMaxResults(userListOptions.getLength()).list(); // Building result ArrayList<User> usersList = new ArrayList<User>(); for (UserHB userToReturnHB : usersHB) { usersList.add((User) userToReturnHB.toPojo()); } userListResult.setTotalUsers(totalUsers); userListResult.setUsersList(usersList); transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) transaction.rollback(); this.errorManager.reportError(resourceManager, dataResult, "getUsers", e); return dataResult; } dataResult.setData(userListResult); dataResult.setSuccess(true); dataResult.setMessage(UserCommand.resourceManager.getMessage("getUsers.success")); return dataResult; }