private DetachedCriteria subquery(SubqueryExpression sqex) {

    String entityName = sqex.getTargetPropertyName();
    String alias = Texts.tos(sqex.getAlias(), null);

    DetachedCriteria dtc;
    if (alias != null) {
      dtc = DetachedCriteria.forEntityName(entityName, alias);
    } else {
      dtc = DetachedCriteria.forEntityName(entityName);
    }
    if (log.isTraceEnabled()) {
      log.trace(
          String.format(
              "Creating detached criteria for entity %s of type %s as %s",
              entityName, sqex.getType(), sqex.getValue()));
    }

    if (sqex.getValue() instanceof Restrictions) {
      Restrictions restr = (Restrictions) sqex.getValue();
      dtc.setProjection(Projections.id());
      dtc.add(parseRestriction(restr));
    } else if (sqex.getValue() instanceof Where) {
      dtc.setProjection(Projections.id());
      DetachedWhereParser whp = new DetachedWhereParser();
      whp.parse((Where) sqex.getValue(), dtc);
    } else {
      throw new IllegalStateException(
          String.format(
              "Subquery must be instance of restrictions or Where, but is %s",
              sqex.getValue().getClass().getName()));
    }

    return dtc;
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testGrantAllResourceToDept() throws Exception {
    // 岗位ID
    String deptId = "8a8140ef4c112cf6014c112d6efd0000";

    // 查询出所有有效的菜单的ID(在权限表中,资源的id对应的是菜单的id)
    List<String> resourceIds =
        session
            .createCriteria(Menu.class)
            .setProjection(Projections.id())
            .add(Restrictions.eq("status", CommonStatus.ACTIVE.getValue()))
            .add(Restrictions.eq("show", true))
            .list();
    Assert.assertNotNull("没有查询到菜单资源数据!", resourceIds);
    Assert.assertTrue("没有查询到菜单资源数据!", !resourceIds.isEmpty());

    logger.info("开始将[菜单资源]授予岗位:" + deptId);
    int i = 0;
    for (String id : resourceIds) {
      AccreditMenu accreditMenu = new AccreditMenu();
      accreditMenu.setResourceId(id);
      accreditMenu.setDeptId(deptId);
      accreditMenu.setId(UUIDGenerator.generate());
      session.save(accreditMenu);
      if (i++ % 10 == 0) {
        session.flush();
        session.clear();
      }
    }
  }
  public void deleteProcessDefinition(ProcessDefinition processDefinition) {
    try {
      // delete all instances of the given process
      List processInstances =
          session
              .createCriteria(ProcessInstance.class)
              .add(Restrictions.eq("processDefinition", processDefinition))
              .setProjection(Projections.id())
              .list();
      for (Iterator iter = processInstances.iterator(); iter.hasNext(); ) {
        Long id = (Long) iter.next();
        ProcessInstance processInstance = (ProcessInstance) session.get(ProcessInstance.class, id);
        if (processInstance != null) deleteProcessInstance(processInstance);
      }

      List referencingProcessStates = findReferencingProcessStates(processDefinition);
      for (Iterator i = referencingProcessStates.iterator(); i.hasNext(); ) {
        ProcessState processState = (ProcessState) i.next();
        processState.setSubProcessDefinition(null);
      }

      // then delete the process definition
      session.delete(processDefinition);
    } catch (HibernateException e) {
      handle(e);
      throw new JbpmPersistenceException("could not delete " + processDefinition, e);
    }
  }
  public boolean exists(PK id) {

    return getSession()
            .createCriteria(entityClass)
            .add(Restrictions.idEq(id))
            .setProjection(Projections.id())
            .uniqueResult()
        != null;
  }
 @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();
 }
  public PaginatedList<Keyword> findKeywords(
      Keyword keyword,
      final boolean ignoreCase,
      final Order order,
      final Integer firstResult,
      final Integer maxResults)
      throws IllegalArgumentException {
    if (keyword == null) {
      throw new IllegalArgumentException("keyword cannot be null");
    }
    final MatchMode matchMode = MatchMode.ANYWHERE;
    Example criterionKeyword = Example.create(keyword);
    criterionKeyword.enableLike(matchMode);
    if (ignoreCase) {
      criterionKeyword.ignoreCase();
    }

    // Normally, Hibernate performs a left-outer join, when searching for
    // an object with collections using Criteria. This returns a ResultSet
    // that contains duplicate objects. In order to get a unique list of
    // Keywords with paginated support, we need to a nested query to find
    // distinct matching ids, then get the Keywords. The end result is a
    // subselect in the main query, but only one query is sent.
    DetachedCriteria dc = DetachedCriteria.forClass(Keyword.class);
    dc.add(criterionKeyword);
    dc.setResultTransformer(DISTINCT_ROOT_ENTITY);

    Conjunction conjunction =
        createTranslationConditions(keyword.getTranslations(), ignoreCase, matchMode);
    if (conjunction != null) dc.createCriteria(FIELD_TRANSLATIONS).add(conjunction);
    dc.setProjection(Projections.id());

    Criteria criteria = getSession().createCriteria(Keyword.class);
    criteria.add(Subqueries.propertyIn(FIELD_ID, dc));
    if (Order.desc == order) criteria.addOrder(desc(FIELD_KEYWORD));
    else criteria.addOrder(asc(FIELD_KEYWORD));
    if (firstResult != null) criteria.setFirstResult(firstResult);
    if (maxResults != null) criteria.setMaxResults(maxResults);

    final List<Keyword> criteriaList = criteria.list();
    int maxListSize = 0;
    if (criteriaList.size() > 0) {
      maxListSize = calculateMaxListSize(criterionKeyword, conjunction);
    }

    return new PaginatedList<Keyword>(criteriaList, maxListSize);
  }
  @Override
  public List<Salon> getByEquipoName(String equipoName) {
    Criterion crit1 = Restrictions.ilike("name", equipoName, MatchMode.ANYWHERE);

    DetachedCriteria subQuery =
        DetachedCriteria.forClass(Salon.class)
            .createCriteria("equipos")
            .add(Restrictions.or(crit1))
            .setProjection(Projections.id());

    Criteria mainCriteria =
        getSession()
            .createCriteria(Salon.class)
            .add(Subqueries.propertyIn("id", subQuery))
            .setFetchMode("equipos", FetchMode.JOIN);

    return mainCriteria.list();
  }
  @Override
  public EncounterQueryResult evaluate(EncounterQuery definition, EvaluationContext context)
      throws EvaluationException {
    context = ObjectUtil.nvl(context, new EvaluationContext());

    BasicEncounterQuery query = (BasicEncounterQuery) definition;
    EncounterQueryResult result = new EncounterQueryResult(query, context);

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setProjection(Projections.id());
    criteria.add(Restrictions.eq("voided", false));

    if (query.getOnOrAfter() != null) {
      criteria.add(Restrictions.ge("encounterDatetime", query.getOnOrAfter()));
    }
    if (query.getOnOrBefore() != null) {
      criteria.add(
          Restrictions.le(
              "encounterDatetime", DateUtil.getEndOfDayIfTimeExcluded(query.getOnOrBefore())));
    }

    if (context.getBaseCohort() != null) {
      if (context.getBaseCohort().size() == 0) {
        return result;
      } else {
        criteria.add(Restrictions.in("patient.id", context.getBaseCohort().getMemberIds()));
      }
    }
    if (context instanceof EncounterEvaluationContext) {
      EncounterIdSet baseEncounters = ((EncounterEvaluationContext) context).getBaseEncounters();
      if (baseEncounters != null) {
        if (baseEncounters.getSize() == 0) {
          return result;
        } else {
          criteria.add(Restrictions.in("id", baseEncounters.getMemberIds()));
        }
      }
    }

    for (Integer encounterId : ((List<Integer>) criteria.list())) {
      result.add(encounterId);
    }
    return result;
  }
 public List<Meeting> getMeetingListByStudyId(int studyId, int rows) {
   return getCurrentSession()
       .createCriteria(Meeting.class)
       .setCacheable(true)
       .add(Restrictions.eq("study.id", studyId))
       .addOrder(Order.desc("id"))
       .setProjection(
           Projections.projectionList()
               .add(Projections.id())
               .add(Projections.property("title"))
               .add(Projections.property("cnt"))
               .add(Projections.property("status"))
               .add(Projections.property("openDate"))
               .add(Projections.property("openTime"))
               .add(Projections.property("closeDate"))
               .add(Projections.property("closeTime")))
       .setMaxResults(rows)
       .list();
 }
Exemple #10
0
 /**
  * Returns the IDs for all the sites visible according to the given parameters. If the parameters
  * indicate that all sites should be visible, it may return null.
  */
 @SuppressWarnings({"unchecked"})
 public Collection<Integer> getVisibleSiteIds(VisibleSiteParameters parameters) {
   if (parameters.isAllManagingSites() || parameters.isAllParticipatingSites()) {
     return null; // shortcut for all
   } else {
     Set<String> idents = new HashSet<String>();
     idents.addAll(parameters.getParticipatingSiteIdentifiers());
     idents.addAll(parameters.getManagingSiteIdentifiers());
     if (idents.isEmpty()) {
       return Collections.emptySet();
     } else {
       return getHibernateTemplate()
           .findByCriteria(
               criteria()
                   .add(MoreRestrictions.in("assignedIdentifier", idents))
                   .setProjection(Projections.id()));
     }
   }
 }
  @Override
  @Transactional
  public Long createComment(
      UserProfile user, String articleDoi, String title, String body, String ciStatement) {
    if (articleDoi == null) {
      throw new IllegalArgumentException("Attempted to create comment with null article id");
    } else if (user == null || user.getID() == null) {
      throw new IllegalArgumentException("Attempted to create comment without a creator");
    } else if (body == null || body.isEmpty()) {
      throw new IllegalArgumentException("Attempted to create comment with no body");
    }

    log.debug(
        "Creating comment on article: {}; title: {}; body: {}",
        new Object[] {articleDoi, title, body});
    Long articleID;
    try {
      articleID =
          (Long)
              hibernateTemplate
                  .findByCriteria(
                      DetachedCriteria.forClass(Article.class)
                          .add(Restrictions.eq("doi", articleDoi))
                          .setProjection(Projections.id()))
                  .get(0);
    } catch (IndexOutOfBoundsException e) {
      throw new IllegalArgumentException("Invalid doi: " + articleDoi);
    }

    // generate an annotation uri
    Annotation comment = new Annotation(user, AnnotationType.COMMENT, articleID);
    comment.setAnnotationUri(URIGenerator.generate(comment));
    comment.setTitle(title);
    comment.setBody(body);
    comment.setCompetingInterestBody(ciStatement);

    Long id = (Long) hibernateTemplate.save(comment);

    return id;
  }
  public static void main(String[] args) {

    // getting SessionFactory from HibernateUtilities.
    SessionFactory sf = HibernateUtilities.getSessionFactory();
    // open session factory using session factory
    Session s = sf.openSession();
    // creating a Criteria instance and setting a projection
    Criteria cr = s.createCriteria("Emp");
    // setting a projection with alias
    //	cr.setProjection(Projections.alias(Projections.id(), "id"));
    cr.setProjection(Projections.id());
    // using the addOrder method on Criteria for sorting of the result
    cr.addOrder(Order.asc("eid"));
    List l = cr.list();
    for (int i = 0; i < l.size(); i++) {
      log.info(l.get(i));
    }

    // close session will release database connection
    s.close();
    // close session factory will release any resources held by hibernate
    sf.close();
  }
 @Override
 public <T extends GettableById> Collection<Integer> getIds(
     Class<T> bookKeywordEntityClass,
     String bookKeywordEntity,
     int offset,
     int limit,
     HashMap<String, FetchMode> fetchMode,
     HashMap<String, String> alias,
     Criterion... criterions) {
   validateTransaction();
   Criteria criteria = getSession().createCriteria(bookKeywordEntityClass, bookKeywordEntity);
   criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
   criteria.setFirstResult(offset);
   if (limit != 0) criteria.setMaxResults(limit);
   for (Criterion restriction : criterions) criteria.add(restriction);
   for (Map.Entry<String, FetchMode> stringObjectEntry : fetchMode.entrySet()) {
     criteria.setFetchMode(stringObjectEntry.getKey(), stringObjectEntry.getValue());
   }
   for (Map.Entry<String, String> stringObjectEntry : alias.entrySet()) {
     criteria.createAlias(stringObjectEntry.getKey(), stringObjectEntry.getValue());
   }
   criteria.setProjection(Projections.id());
   return criteria.list();
 }