示例#1
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  protected int countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
      orderEntries =
          (List<CriteriaImpl.OrderEntry>) ReflectionUtils.getFieldValue(impl, "orderEntries");
      ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
      logger.error("", e);
    }

    int totalCount = (Integer) c.setProjection(Projections.rowCount()).uniqueResult();

    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);
    }

    return totalCount;
  }
  @Scheduled(fixedDelay = 60000)
  public void changeSessionStatus() {

    List<CurrentUsersDTO> allList = null;
    List<CurrentUsersDTO> activeList = null;

    String currentTime = getTime();
    String beforeTime = getBeforeTime();
    String beforeHeartBeatTime = getBeforeHeartBeatTime();

    Session session = getSession();
    session.getTransaction().begin();

    Criteria criteria =
        session
            .createCriteria(SessionDetails.class, "sessionDetails")
            .add(
                Restrictions.between(
                    "sessionDetails.heartBeatTime", beforeHeartBeatTime, currentTime))
            .add(Restrictions.between("sessionDetails.lastAccessTime", beforeTime, currentTime));
    criteria.addOrder(Order.asc("SID"));
    criteria.setProjection(
        Projections.projectionList()
            .add(Projections.property("SID").as("sid"))
            .add(Projections.property("lastAccessTime").as("lastAccessTime")));
    activeList =
        criteria.setResultTransformer(Transformers.aliasToBean(CurrentUsersDTO.class)).list();

    Criteria criteria1 = session.createCriteria(SessionDetails.class, "sessionDetails");
    criteria1.addOrder(Order.asc("SID"));
    criteria1.setProjection(
        Projections.projectionList()
            .add(Projections.property("SID").as("sid"))
            .add(Projections.property("lastAccessTime").as("lastAccessTime")));
    allList =
        criteria1.setResultTransformer(Transformers.aliasToBean(CurrentUsersDTO.class)).list();

    for (CurrentUsersDTO dto : allList) {
      try {
        SessionDetails sd = getById(dto.getSid());
        sd.setStatus("INACTIVE");
        saveSessionDetails(sd);
      } catch (Exception e) {
        System.out.println("E :" + e);
      }
    }

    for (CurrentUsersDTO dto : activeList) {
      try {
        SessionDetails sd = getById(dto.getSid());
        sd.setStatus("ACTIVE");
        saveSessionDetails(sd);
      } catch (Exception e) {
        System.out.println("E :" + e);
      }
    }
    session.getTransaction().commit();
    session.close();
  }
示例#3
0
  @Override
  @SuppressWarnings("unchecked")
  public void cleanupDatabase() {
    Criteria allTagEntriesCrit = getSession().createCriteria(RecipeCategoryEntry.class);
    List<RecipeCategoryEntry> usedTagEntries = allTagEntriesCrit.list();

    Set<Long> usedTagIds = new HashSet<Long>();

    for (RecipeCategoryEntry usedTag : usedTagEntries) {
      usedTagIds.add(usedTag.getCategory().getId());
    }

    Criteria unusedTagsCrit = getSession().createCriteria(RecipeCategory.class);
    unusedTagsCrit.add(Restrictions.not(Restrictions.in("id", usedTagIds)));
    unusedTagsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria allIngrEntriesCrit = getSession().createCriteria(RecipeIngredientEntry.class);
    List<RecipeIngredientEntry> usedIngrEntries = allIngrEntriesCrit.list();

    Set<Long> usedIngrIds = new HashSet<Long>();
    Set<Long> usedIngrGrpIds = new HashSet<Long>();

    for (RecipeIngredientEntry usedIngr : usedIngrEntries) {
      usedIngrIds.add(usedIngr.getIngredient().getId());
      usedIngrGrpIds.add(usedIngr.getGroup().getId());
    }

    Criteria unusedIngrsCrit = getSession().createCriteria(RecipeIngredient.class);
    unusedIngrsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrIds)));
    unusedIngrsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    Criteria unusedIngrGrpsCrit = getSession().createCriteria(RecipeIngredientGroup.class);
    unusedIngrGrpsCrit.add(Restrictions.not(Restrictions.in("id", usedIngrGrpIds)));
    unusedIngrGrpsCrit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    /** ************* */
    for (Object objToDel : unusedTagsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrsCrit.list()) {
      getSession().delete(objToDel);
    }

    for (Object objToDel : unusedIngrGrpsCrit.list()) {
      getSession().delete(objToDel);
    }
  }
 /**
  * 使用指定查询对象进行分页查询.
  *
  * @param criteria 实体的查询对象
  * @param pageNo 页号,从1开始.
  * @param pageSize 每页中的记录数
  * @return 当前页的分页对象
  */
 public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) {
   CriteriaImpl impl = (CriteriaImpl) criteria;
   // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
   Projection projection = impl.getProjection();
   List<CriteriaImpl.OrderEntry> orderEntries;
   try {
     orderEntries = (List) BeanUtils.getPrivateProperty(impl, "orderEntries");
     BeanUtils.setPrivateProperty(impl, "orderEntries", new ArrayList());
   } catch (Exception e) {
     logger.error(e.getMessage());
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 执行查询
   long totalCount =
       ((Number) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
   // 将之前的Projection和OrderBy条件重新设回去
   criteria.setProjection(projection);
   if (projection == null) {
     criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
   }
   try {
     BeanUtils.setPrivateProperty(impl, "orderEntries", orderEntries);
   } catch (Exception e) {
     logger.error(e.getMessage());
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 返回分页对象
   if (totalCount < 1) return new Page();
   int startIndex = Page.getStartOfPage(pageNo, pageSize);
   List list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
   return new Page(startIndex, totalCount, pageSize, list);
 }
示例#5
0
 /**
  * 分页查询函数,使用已设好查询条件与排序的<code>Criteria</code>.
  *
  * @param pageNo 页号,从1开始.
  * @return 含总记录数和当前页数据的Page对象.
  */
 @SuppressWarnings("unchecked")
 public Page<T> pagedQuery(Criteria criteria, int pageNo, int pageSize) {
   Assert.notNull(criteria);
   Assert.isTrue(pageNo >= 1, "pageNo should start from 1");
   CriteriaImpl impl = (CriteriaImpl) criteria;
   // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
   Projection projection = impl.getProjection();
   List<CriteriaImpl.OrderEntry> orderEntries;
   try {
     orderEntries = (List) BeanUtils.forceGetProperty(impl, "orderEntries");
     BeanUtils.forceSetProperty(impl, "orderEntries", new ArrayList());
   } catch (Exception e) {
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 执行查询
   long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
   // 将之前的Projection和OrderBy条件重新设回去
   criteria.setProjection(projection);
   if (projection == null) {
     criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
   }
   try {
     BeanUtils.forceSetProperty(impl, "orderEntries", orderEntries);
   } catch (Exception e) {
     throw new InternalError(" Runtime Exception impossibility throw ");
   }
   // 返回分页对象
   if (totalCount < 1) return new Page<T>();
   int startIndex = Page.getStartOfPage(pageNo, pageSize);
   ;
   List<T> list = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
   return new Page(startIndex, totalCount, pageSize, list);
 }
示例#6
0
  public ArrayList<Country> getCountries() {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<Country> list = new ArrayList<Country>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblCountry.class, "country");
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblCountry> countries = cr.list();
      if (countries.size() > 0) {
        for (Iterator<TblCountry> iterator = countries.iterator(); iterator.hasNext(); ) {
          TblCountry tblcountry = iterator.next();
          Country country = new Country();
          country.convertFromTable(tblcountry);
          list.add(country);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
示例#7
0
  public ArrayList<City> getCitiesByZone(int idzone) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<City> list = new ArrayList<City>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblCity.class, "city");
      cr.createAlias("city.zone", "zone");
      cr.add(Restrictions.eq("zone.idzone", idzone));
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblCity> cities = cr.list();
      if (cities.size() > 0) {
        for (Iterator<TblCity> iterator = cities.iterator(); iterator.hasNext(); ) {
          TblCity tblcity = iterator.next();
          City city = new City();
          city.convertFromTable(tblcity);
          list.add(city);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
示例#8
0
  @SuppressWarnings("unchecked")
  public List<T> findByCriteria(
      final int firstResult,
      final int maxResults,
      final ProjectionList projections,
      final Criterion... criterion) {

    Session session = (Session) getEntityManager().getDelegate();
    Criteria crit = session.createCriteria(getEntityClass());
    crit.setProjection(projections);
    crit.setResultTransformer(Transformers.aliasToBean(getEntityClass()));
    for (final Criterion c : criterion) {
      crit.add(c);
    }

    if (firstResult > 0) {
      crit.setFirstResult(firstResult);
    }

    if (maxResults > 0) {
      crit.setMaxResults(maxResults);
    }

    final List<T> result = crit.list();
    return result;
  }
  public List<UserCountDTO> getCurrentUserCountList(
      String sortField, int order, int start, int gridTableSize, String searchq) throws Exception {
    int count = start;

    List<UserCountDTO> dtoList = null;
    List<UserCountDTO> dtoListCount = new ArrayList<UserCountDTO>();

    Session session = getSession();
    session.getTransaction().begin();

    Criteria criteria =
        session
            .createCriteria(SessionDetails.class, "sessionDetails")
            .add(Restrictions.eq("status", "ACTIVE"));
    criteria.addOrder(Order.asc("SID"));
    criteria.setFirstResult(start).setMaxResults(gridTableSize);
    criteria.setProjection(Projections.projectionList().add(Projections.property("SID").as("sid")));

    dtoList = criteria.setResultTransformer(Transformers.aliasToBean(UserCountDTO.class)).list();
    session.getTransaction().commit();
    session.close();

    if (dtoList.size() > 0) {
      for (UserCountDTO dto : dtoList) {
        dto.setCountId(count + 1);
        dtoListCount.add(dto);
        count += 1;
      }
    }
    return dtoListCount;
  }
  public List<SessionTimeOutDTO> getSessionIDListBySID(Long sid) {
    List<SessionTimeOutDTO> dtoList = null;
    SessionTimeOutDTO dto = null;

    Session session = getSession();
    session.getTransaction().begin();

    Criteria criteria =
        session
            .createCriteria(SessionDetails.class, "sessionDetails")
            .add(Restrictions.eq("SID", sid));
    criteria.setProjection(
        Projections.projectionList()
            .add(Projections.property("SID").as("sid"))
            .add(Projections.property("sessionId").as("sessionId")));
    dto =
        (SessionTimeOutDTO)
            criteria
                .setResultTransformer(Transformers.aliasToBean(SessionTimeOutDTO.class))
                .uniqueResult();

    session.getTransaction().commit();
    session.close();

    dtoList = getList(dto);
    return dtoList;
  }
 @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<WordType> findAllWordTypes() {
   Criteria criteria = createEntityCriteria().addOrder(Order.asc("text"));
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // To avoid duplicates.
   List<WordType> wordtypes = (List<WordType>) criteria.list();
   return wordtypes;
 }
示例#13
0
  public ArrayList<Zone> getZones(int idcountry) {
    Session session = HibernateUtils.getSessionFactory().openSession();
    ArrayList<Zone> list = new ArrayList<Zone>();
    try {
      session.clear();
      Criteria cr = session.createCriteria(TblZone.class, "zone");
      cr.createAlias("zone.country", "country");
      cr.add(Restrictions.eq("country.idcountry", idcountry));
      cr.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
      List<TblZone> zones = cr.list();
      if (zones.size() > 0) {
        for (Iterator<TblZone> iterator = zones.iterator(); iterator.hasNext(); ) {
          TblZone tblzone = iterator.next();
          Zone zone = new Zone();
          zone.convertFromTable(tblzone);
          list.add(zone);
        }
      }
      session.clear();
    } catch (HibernateException e) {
      System.err.println("ERROR IN LIST!!!!!!");
      e.printStackTrace();
      throw new ExceptionInInitializerError(e);
    } finally {

      session.close();
    }
    return list;
  }
  @SuppressWarnings("unchecked")
  public List<T> getAll() {

    Criteria criteria = getSession().createCriteria(this.clazz);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return criteria.list();
  }
示例#15
0
 /**
  * 使用检索标准对象分页查询
  *
  * @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;
 }
示例#16
0
 @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;
 }
  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;
  }
  @SuppressWarnings("unchecked")
  @Override
  public Collection<FuncionarioAreaTrabajoDTO> consultarFuncionarioAreaTrabajoPorAreaTrabajo(
      Integer codigoAreaTrabajo, String userId, Integer codigoCompania, String usuarioSesion)
      throws SICException {
    try {

      Criteria criteria =
          sessionFactory.getCurrentSession().createCriteria(FuncionarioAreaTrabajoDTO.class);
      criteria.setProjection(
          Projections.projectionList()
              .add(Projections.property("usuarioDTO.userId"), "funcionarioDTO.usuarioDTO.userId")
              .add(
                  Projections.property("usuarioDTO.userCompleteName"),
                  "funcionarioDTO.usuarioDTO.userCompleteName")
              .add(
                  Projections.property("usuarioDTO.userName"), "funcionarioDTO.usuarioDTO.userName")
              .add(
                  Projections.property("areaTrabajoDTO.nombreAreaTrabajo"),
                  "areaTrabajoDTO.nombreAreaTrabajo")
              .add(Projections.property("id.codigoCompania"), "id.codigoCompania")
              .add(Projections.property("id.codigoFuncionario"), "id.codigoFuncionario")
              .add(Projections.property("id.codigoAreaTrabajo"), "id.codigoAreaTrabajo"));

      criteria.createAlias("funcionarioDTO", "funcionarioDTO");
      criteria.createAlias("funcionarioDTO.usuarioDTO", "usuarioDTO");

      criteria.createAlias("areaTrabajoDTO", "areaTrabajoDTO");

      criteria.add(Restrictions.eq("estado", SICConstantes.ESTADO_ACTIVO_LITERAL));
      criteria.add(
          Restrictions.eq("funcionarioDTO.estadoFuncionario", SICConstantes.ESTADO_ACTIVO_LITERAL));
      criteria.add(
          Restrictions.eq("areaTrabajoDTO.estadoAreaTrabajo", SICConstantes.ESTADO_ACTIVO_LITERAL));

      criteria.add(Restrictions.eq("id.codigoCompania", codigoCompania));
      criteria.add(Restrictions.eq("areaTrabajoDTO.id.codigoAreaTrabajo", codigoAreaTrabajo));
      criteria.add(Restrictions.ne("usuarioDTO.userName", usuarioSesion));

      // si el usuario ingresa un nombre o usuario de un funcionario
      if (StringUtils.isNotEmpty(userId)) {
        Disjunction disjunction = Restrictions.disjunction();
        disjunction.add(Restrictions.ilike("usuarioDTO.userName", userId, MatchMode.ANYWHERE));
        disjunction.add(
            Restrictions.ilike("usuarioDTO.userCompleteName", userId, MatchMode.ANYWHERE));
        criteria.add(disjunction);
      }
      criteria.setResultTransformer(new DtoResultTransformer(FuncionarioAreaTrabajoDTO.class));

      Collection<FuncionarioAreaTrabajoDTO> funcionarioAreaTrabajoDTOCol = criteria.list();

      return funcionarioAreaTrabajoDTOCol;

    } catch (HibernateException e) {
      throw new SICException("Error consultarFuncionarioAreaTrabajoPorAreaTrabajo: ", e);
    } catch (Exception e) {
      throw new SICException("Error consultarFuncionarioAreaTrabajoPorAreaTrabajo ", e);
    }
  }
  @Override
  public List<Contacto> findAll() {
    Criteria criteria = createEntityCriteria();
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // To avoid duplicates.
    List<Contacto> contacto = (List<Contacto>) criteria.list();

    return contacto;
  }
示例#20
0
  @Override
  public List<WmsUser> findAllWmsUsers() {
    Session session = getSession();
    Criteria criteria = session.createCriteria(WmsUser.class);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    return criteria.list();
  }
 @Override
 public <T extends GettableById> Number count(Class<T> currentClass, Criterion... restrictions) {
   validateTransaction();
   Criteria criteria = getSession().createCriteria(currentClass);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.setProjection(Projections.rowCount());
   for (Criterion restriction : restrictions) criteria.add(restriction);
   return ((Number) criteria.uniqueResult());
 }
 @SuppressWarnings("unchecked") // Hibernate
 public List<GeometryEntity> getGeometriesOrderedByTimestamp(DbQuery parameters) {
   Criteria criteria = session.createCriteria(SamplingGeometryEntity.class);
   DetachedCriteria filter = parameters.createDetachedFilterCriteria("pkid");
   criteria.add(Subqueries.propertyIn(COLUMN_SERIES_PKID, filter));
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.addOrder(Order.asc(COLUMN_TIMESTAMP));
   parameters.addSpatialFilterTo(criteria, parameters);
   return (List<GeometryEntity>) criteria.list();
 }
 @Override
 public <T extends GettableById> Collection<Integer> getIds(
     Class<T> currentClass, Criterion... restrictions) {
   validateTransaction();
   Criteria criteria = getSession().createCriteria(currentClass);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.setProjection(Projections.id());
   for (Criterion restriction : restrictions) criteria.add(restriction);
   return criteria.list();
 }
  private Criteria createAutoMobileCriteria(
      Session session, AutomobileExpense autoMobile, String matchType) {
    Criteria criteria = session.createCriteria(AutomobileExpense.class);

    if (autoMobile.getReimbursement1() != null) {
      criteria.add(Restrictions.eq("reimbursement1", autoMobile.getReimbursement1()));
    }
    criteria.setResultTransformer(criteria.DISTINCT_ROOT_ENTITY);
    return criteria;
  }
示例#25
0
  private <P> Criteria buildProjectionCriteria(
      Class<P> projectClass, Criteria criteria, Projection projections, boolean distinctResult) {
    if (distinctResult) {
      criteria.setProjection(Projections.distinct(projections));
    } else {
      criteria.setProjection(projections);
    }

    return criteria.setResultTransformer(Transformers.aliasToBean(projectClass));
  }
  @SuppressWarnings("unchecked")
  @Override
  public List<Schema> findByDataBase(long dataBaseId) {
    Criteria criteria = getSession().createCriteria(Schema.class);

    criteria.setFetchMode("dataBase", FetchMode.JOIN);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    criteria.add(Restrictions.eq("dataBase.id", dataBaseId));

    return criteria.list();
  }
 @Override
 public <T extends GettableById> List<T> get(
     Class<T> bookEntityClass, int from, int to, Criterion... restrictions) {
   validateTransaction();
   Criteria criteria = getSession().createCriteria(bookEntityClass);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.setFirstResult(from);
   if (to != 0) criteria.setMaxResults(to);
   for (Criterion restriction : restrictions) criteria.add(restriction);
   return criteria.list();
 }
示例#28
0
  @SuppressWarnings("unchecked")
  public List<T> getAll() {

    final Session session = this.sessionFactory.getCurrentSession();
    final Criteria criteria = session.createCriteria(this.type);
    criteria.add(Restrictions.eq("deleted", false));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    criteria.setFetchMode("*", FetchMode.JOIN);

    return criteria.list();
  }
示例#29
0
 public List<User> findAllUsers() {
   Criteria criteria = createEntityCriteria().addOrder(Order.asc("firstName"));
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // To exclude duplicates.
   List<User> users = criteria.list();
   // Lazy load.
   // Uncomment below lines for eagerly fetching of userProfiles.
   /*
   for(User user : users){
       Hibernate.initialize(user.getUserProfiles());
   }*/
   return users;
 }
  public List<TaskInstance> findTaskInstances(
      long processInstanceId,
      long tokenId,
      String[] actorIds,
      boolean pooledActors,
      Boolean completed,
      int start,
      int end,
      OrderByComparator orderByComparator) {

    if ((actorIds != null) && (actorIds.length == 0)) {
      return Collections.emptyList();
    }

    try {
      Criteria criteria = _session.createCriteria(TaskInstance.class);

      criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

      if (processInstanceId > 0) {
        criteria.add(Restrictions.eq("processInstance.id", processInstanceId));
      } else if (tokenId > 0) {
        criteria.add(Restrictions.eq("token.id", tokenId));
      }

      if (actorIds != null) {
        if (pooledActors) {
          Criteria subcriteria = criteria.createCriteria("pooledActors");

          subcriteria.add(Restrictions.in("actorId", actorIds));

          criteria.add(Restrictions.isNull("actorId"));
        } else {
          criteria.add(Restrictions.in("actorId", actorIds));
        }
      }

      if (completed != null) {
        if (completed.booleanValue()) {
          criteria.add(Restrictions.isNotNull("end"));
        } else {
          criteria.add(Restrictions.isNull("end"));
        }
      }

      addPagination(criteria, start, end);
      addOrder(criteria, orderByComparator);

      return criteria.list();
    } catch (Exception e) {
      throw new JbpmException(e);
    }
  }