@Test
  public void testSimpleCrossTxnWork() {
    Session session1 = injector.getInstance(SessionFactory.class).openSession();
    ManagedSessionContext.bind(session1);
    HibernateTestEntity entity =
        injector
            .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
            .runOperationInTxn();
    injector
        .getInstance(ManualLocalTransactionsWithCustomMatchersTest.TransactionalObject.class)
        .runOperationInTxn2();

    assert injector.getInstance(Session.class).contains(entity)
        : "Session appears to have been closed across txns!";
    session1.close();

    // try to query them back out

    Session session = injector.getInstance(SessionFactory.class).openSession();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT))
            .uniqueResult();
    assert null
        != session
            .createCriteria(HibernateTestEntity.class)
            .add(Expression.eq("text", UNIQUE_TEXT_2))
            .uniqueResult();
    session.close();
  }
示例#2
0
 public Label findByName(String name, long parent) {
   final DetachedCriteria criteria = newCriteria();
   criteria.add(Expression.eq("parentId", parent));
   criteria.add(Expression.eq("name", name));
   final List<Label> labels = findByCriteria(criteria);
   return labels.size() > 0 ? labels.get(0) : null;
 }
  public boolean isDuplicateWeblogCategoryName(WeblogCategoryData cat) throws RollerException {
    // ensure that no sibling categories share the same name
    WeblogCategoryData parent =
        null == cat.getId() ? (WeblogCategoryData) cat.getNewParent() : cat.getParent();

    if (null != parent) // don't worry about root
    {
      List sameNames;
      try {
        Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
        Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
        criteria.createAlias("category", "c");
        criteria.add(Expression.eq("c.name", cat.getName()));
        criteria.add(Expression.eq("ancestorCategory", parent));
        criteria.add(Expression.eq("relation", Assoc.PARENT));
        sameNames = criteria.list();
      } catch (HibernateException e) {
        throw new RollerException(e);
      }
      if (sameNames.size() > 0) {
        return true;
      }
    }
    return false;
  }
 @Override
 public TbData getTbData(final Encounter encounter, final Concept question) {
   Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(TbData.class);
   criteria.add(Expression.eq("encounter", encounter));
   criteria.add(Expression.eq("question", question));
   return (TbData) criteria.uniqueResult();
 }
示例#5
0
 private Criterion findbyAnd(String type, String str) {
   Criterion criterion = null;
   List<String> srch = new ArrayList<String>();
   String[] srchAND = str.split(" and ");
   for (int i = 0; i < srchAND.length; i++) {
     String[] srch_ = srchAND[i].split(" ");
     for (int j = 0; j < srch_.length; j++) {
       if (cn.jsprun.utils.FormDataCheck.isValueString(srch_[j])) {
         srch.add(srch_[j]);
       }
     }
   }
   try {
     Criterion[] criterionArray = new Criterion[srch.size()];
     for (int i = 0; i < srch.size(); i++) {
       Criterion criterionCount = Expression.like(type, srch.get(i), MatchMode.ANYWHERE);
       criterionArray[i] = criterionCount;
     }
     for (int i = 0; i < criterionArray.length; i++) {
       if (i == 0) {
         criterion = Expression.and(criterionArray[i], criterionArray[i++]);
       } else {
         criterion = Expression.and(criterion, criterionArray[i]);
       }
     }
   } catch (HibernateException e) {
     e.printStackTrace();
     criterion = null;
   }
   return criterion;
 }
  public String createAnchor(WeblogEntryData entry) throws RollerException {
    try {
      // Check for uniqueness of anchor
      String base = entry.createAnchorBase();
      String name = base;
      int count = 0;

      while (true) {
        if (count > 0) {
          name = base + count;
        }

        Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
        Criteria criteria = session.createCriteria(WeblogEntryData.class);
        criteria.add(Expression.eq("website", entry.getWebsite()));
        criteria.add(Expression.eq("anchor", name));

        List results = criteria.list();

        if (results.size() < 1) {
          break;
        } else {
          count++;
        }
      }
      return name;
    } catch (HibernateException e) {
      throw new RollerException(e);
    }
  }
  public List getWeblogEntries(WeblogCategoryData cat, boolean subcats) throws RollerException {
    try {
      Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
      List entries = new LinkedList();

      if (subcats) {
        // Get entries in subcategories
        Criteria assocsQuery = session.createCriteria(WeblogCategoryAssoc.class);
        assocsQuery.add(Expression.eq("ancestorCategory", cat));
        Iterator assocs = assocsQuery.list().iterator();
        while (assocs.hasNext()) {
          WeblogCategoryAssoc assoc = (WeblogCategoryAssoc) assocs.next();
          Criteria entriesQuery = session.createCriteria(WeblogEntryData.class);
          entriesQuery.add(Expression.eq("category", assoc.getCategory()));
          Iterator entryIter = entriesQuery.list().iterator();
          while (entryIter.hasNext()) {
            WeblogEntryData entry = (WeblogEntryData) entryIter.next();
            entries.add(entry);
          }
        }
      }

      // Get entries in category
      Criteria entriesQuery = session.createCriteria(WeblogEntryData.class);
      entriesQuery.add(Expression.eq("category", cat));
      Iterator entryIter = entriesQuery.list().iterator();
      while (entryIter.hasNext()) {
        WeblogEntryData entry = (WeblogEntryData) entryIter.next();
        entries.add(entry);
      }
      return entries;
    } catch (HibernateException e) {
      throw new RollerException(e);
    }
  }
示例#8
0
 /**
  * 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));
   }
 }
示例#9
0
 public List<Label> getByExmaple(Label example) {
   DetachedCriteria criteria = newCriteria();
   if (example.getParentId() != null)
     criteria.add(Expression.eq("parentId", example.getParentId()));
   if (example.getName() != null)
     criteria.add(Expression.ilike("name", example.getName(), MatchMode.START));
   criteria.addOrder(Order.asc("name"));
   return findByCriteria(criteria);
 }
  public static void main(String[] args) throws Exception {
    Criteria c = HibernateUtil.currentSession().createCriteria(GuiaSimples.class);
    c.add(Expression.ge("dataAtendimento", Utils.parse("21/02/2008")));
    c.add(Expression.le("dataAtendimento", Utils.parse("20/07/2008")));
    c.add(Expression.in("situacao.descricao", situacoes));

    alimentarMapa(c.list());

    processarArquivo();
  }
 public List getWeblogCategoryChildAssocs(WeblogCategoryData cat) throws RollerException {
   try {
     Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
     Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
     criteria.add(Expression.eq("ancestorCategory", cat));
     criteria.add(Expression.eq("relation", Assoc.PARENT));
     return criteria.list();
   } catch (HibernateException e) {
     throw new RollerException(e);
   }
 }
示例#12
0
  /** @see org.openmrs.notification.AlertService#getAllAlerts(boolean) */
  @SuppressWarnings("unchecked")
  public List<Alert> getAllAlerts(boolean includeExpired) throws DAOException {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Alert.class);

    // exclude the expired alerts unless requested
    if (includeExpired == false)
      crit.add(
          Expression.or(
              Expression.isNull("dateToExpire"), Expression.gt("dateToExpire", new Date())));

    return crit.list();
  }
 /** @see SerializedObjectDAO#getAllObjects(Class, boolean) */
 @SuppressWarnings("unchecked")
 public List<SerializedObject> getAllSerializedObjects(Class<?> type, boolean includeRetired)
     throws DAOException {
   Criteria c = sessionFactory.getCurrentSession().createCriteria(SerializedObject.class);
   c.add(
       Expression.or(
           Expression.eq("type", type.getName()), Expression.eq("subtype", type.getName())));
   if (!includeRetired) {
     c.add(Expression.like("retired", false));
   }
   return (List<SerializedObject>) c.list();
 }
  /** @see org.openmrs.api.db.LocationDAO#getCountOfLocations(String, Boolean) */
  @Override
  public Long getCountOfLocations(String nameFragment, Boolean includeRetired) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Location.class);
    if (!includeRetired) criteria.add(Expression.eq("retired", false));

    if (StringUtils.isNotBlank(nameFragment))
      criteria.add(Expression.ilike("name", nameFragment, MatchMode.START));

    criteria.setProjection(Projections.rowCount());

    return (Long) criteria.uniqueResult();
  }
  /** @see LocationDAO#getRootLocations(boolean) */
  @SuppressWarnings("unchecked")
  @Override
  public List<Location> getRootLocations(boolean includeRetired) throws DAOException {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Location.class);
    if (!includeRetired) criteria.add(Expression.eq("retired", false));

    criteria.add(Expression.isNull("parentLocation"));

    criteria.addOrder(Order.asc("name"));
    return criteria.list();
  }
  public WeblogEntryData getWeblogEntryByAnchor(WebsiteData website, String anchor)
      throws RollerException {

    if (website == null) throw new RollerException("Website is null");

    if (anchor == null) throw new RollerException("Anchor is null");

    // mapping key is combo of weblog + anchor
    String mappingKey = website.getHandle() + ":" + anchor;

    // check cache first
    // NOTE: if we ever allow changing anchors then this needs updating
    if (this.entryAnchorToIdMap.containsKey(mappingKey)) {

      WeblogEntryData entry = this.getWeblogEntry((String) this.entryAnchorToIdMap.get(mappingKey));
      if (entry != null) {
        log.debug("entryAnchorToIdMap CACHE HIT - " + mappingKey);
        return entry;
      } else {
        // mapping hit with lookup miss?  mapping must be old, remove it
        this.entryAnchorToIdMap.remove(mappingKey);
      }
    }

    // cache failed, do lookup
    try {
      Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
      Criteria criteria = session.createCriteria(WeblogEntryData.class);
      criteria.add(
          Expression.conjunction()
              .add(Expression.eq("website", website))
              .add(Expression.eq("anchor", anchor)));
      criteria.addOrder(Order.desc("pubTime"));
      criteria.setMaxResults(1);

      List list = criteria.list();

      WeblogEntryData entry = null;
      if (list.size() != 0) {
        entry = (WeblogEntryData) criteria.uniqueResult();
      }

      // add mapping to cache
      if (entry != null) {
        log.debug("entryAnchorToIdMap CACHE MISS - " + mappingKey);
        this.entryAnchorToIdMap.put(mappingKey, entry.getId());
      }

      return entry;
    } catch (HibernateException e) {
      throw new RollerException(e);
    }
  }
 /** @see SerializedObjectDAO#getAllObjectsByName(Class, String) */
 @SuppressWarnings("unchecked")
 public List<SerializedObject> getAllSerializedObjectsByName(
     Class<?> type, String name, boolean exactMatchOnly) throws DAOException {
   Criteria c = sessionFactory.getCurrentSession().createCriteria(SerializedObject.class);
   c.add(
       Expression.or(
           Expression.eq("type", type.getName()), Expression.eq("subtype", type.getName())));
   if (exactMatchOnly) {
     c.add(Expression.eq("name", name));
   } else {
     c.add(Expression.ilike("name", name, MatchMode.ANYWHERE));
   }
   return (List<SerializedObject>) c.list();
 }
 public boolean isDescendentOf(WeblogCategoryData child, WeblogCategoryData ancestor)
     throws RollerException {
   boolean ret = false;
   try {
     Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
     Criteria criteria = session.createCriteria(WeblogCategoryAssoc.class);
     criteria.add(Expression.eq("category", child));
     criteria.add(Expression.eq("ancestorCategory", ancestor));
     ret = criteria.list().size() > 0;
   } catch (HibernateException e) {
     throw new RollerException(e);
   }
   return ret;
 }
 @Override
 public List<?> findSysCompanyUserRel(SysCompanyUserRel object) throws Exception {
   if (null == object) {
     return super.loadAll(object.getClass());
   } else {
     DetachedCriteria criteria = DetachedCriteria.forClass(object.getClass());
     if (object.getId().getParentUserId() != null && object.getId().getParentUserId() > 0) {
       criteria.add(Expression.eq("id.parentUserId", object.getId().getParentUserId()));
     }
     if (object.getId().getChildUserId() != null && object.getId().getChildUserId() > 0) {
       criteria.add(Expression.eq("id.childUserId", object.getId().getChildUserId()));
     }
     return super.findByCriteria(criteria);
   }
 }
  public boolean isWeblogCategoryInUse(WeblogCategoryData cat) throws RollerException {
    try {
      Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();
      Criteria criteria = session.createCriteria(WeblogEntryData.class);
      criteria.add(Expression.eq("category", cat));
      criteria.setMaxResults(1);
      int entryCount = criteria.list().size();

      if (entryCount > 0) {
        return true;
      }

      Iterator cats = cat.getWeblogCategories().iterator();
      while (cats.hasNext()) {
        WeblogCategoryData childCat = (WeblogCategoryData) cats.next();
        if (childCat.isInUse()) {
          return true;
        }
      }

      if (cat.getWebsite().getBloggerCategory().equals(cat)) {
        return true;
      }

      if (cat.getWebsite().getDefaultCategory().equals(cat)) {
        return true;
      }

      return false;
    } catch (HibernateException e) {
      throw new RollerException(e);
    }
  }
 @Override
 public List<TbData> findTbDataByEncounter(final Encounter encounter) {
   Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(TbData.class);
   criteria.add(Expression.eq("encounter", encounter));
   criteria.addOrder(Order.asc("question"));
   return criteria.list();
 }
 @Override
 public List<TbData> findTbDataByPatient(final Patient patient) {
   Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(TbData.class);
   criteria.add(Expression.eq("patient", patient));
   criteria.addOrder(Order.asc("encounterDatetime"));
   return criteria.list();
 }
示例#23
0
 private Criterion findbyOR(String type, String str, Session session) {
   Criterion criterion = null;
   StringBuffer sbSQL = new StringBuffer("select p.pmid from Pms as p where");
   List<String> srch = new ArrayList<String>();
   str = str.replace("|", ",");
   String[] srchAND = str.split(" and ");
   for (int i = 0; i < srchAND.length; i++) {
     String[] srch_ = srchAND[i].split(" ");
     for (int j = 0; j < srch_.length; j++) {
       if (cn.jsprun.utils.FormDataCheck.isValueString(srch_[j])) {
         srch.add(srch_[j]);
       }
     }
   }
   for (int i = 0; i < srch.size(); i++) {
     sbSQL.append(" p." + type + " like '%" + srch.get(i) + "%' or");
   }
   String sql = sbSQL.substring(0, sbSQL.length() - 2);
   try {
     Query query = session.createQuery(sql);
     List<Integer> list = query.list();
     criterion = Expression.in("pmid", list);
     session.flush();
   } catch (HibernateException e) {
     e.printStackTrace();
     criterion = null;
   }
   return criterion;
 }
  private void removeWeblogEntryContents(WeblogEntryData entry) throws RollerException {

    if (entry == null) {
      throw new RollerException("cannot remove null entry");
    }

    Session session = ((HibernatePersistenceStrategy) this.strategy).getSession();

    // remove referers
    Criteria refererQuery = session.createCriteria(RefererData.class);
    refererQuery.add(Expression.eq("weblogEntry", entry));
    List referers = refererQuery.list();
    for (Iterator iter = referers.iterator(); iter.hasNext(); ) {
      RefererData referer = (RefererData) iter.next();
      this.strategy.remove(referer);
    }

    // remove comments
    List comments =
        getComments(
            null, // website
            entry, null, // search String
            null, // startDate
            null, // endDate
            null, // pending
            null, // approved
            null, // spam
            true, // reverse chrono order (not that it matters)
            0, // offset
            -1); // no limit
    Iterator commentsIT = comments.iterator();
    while (commentsIT.hasNext()) {
      this.strategy.remove((CommentData) commentsIT.next());
    }
  }
示例#25
0
  /**
   * @see org.openmrs.api.db.ObsDAO#getAllMimeTypes(boolean)
   * @deprecated
   */
  @SuppressWarnings("unchecked")
  public List<MimeType> getAllMimeTypes(boolean includeRetired) throws DAOException {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(MimeType.class);

    if (includeRetired == false) crit.add(Expression.eq("retired", Boolean.FALSE));

    return crit.list();
  }
  public void testJunctionNotExpressionQBE() throws Exception {
    deleteData();
    initData();
    Session s = openSession();
    Transaction t = s.beginTransaction();
    Componentizable master = getMaster("hibernate", null, "ope%");
    Criteria crit = s.createCriteria(Componentizable.class);
    Example ex = Example.create(master).enableLike();

    crit.add(Expression.or(Expression.not(ex), ex));

    List result = crit.list();
    assertNotNull(result);
    assertEquals(2, result.size());
    t.commit();
    s.close();
  }
  public Long getQuantidade(Class<? extends Segurado> klass, String situacao) {
    Criteria criteria = HibernateUtil.currentSession().createCriteria(klass);

    criteria
        .add(Expression.eq("situacao.descricao", situacao))
        .setProjection(Projections.rowCount());

    return (Long) criteria.uniqueResult();
  }
  /**
   * Gets a list of all calendars available sorted by primary key.
   *
   * @return List of Calendar
   * @throws Exception
   */
  public Set getCalendarList(List roles, List groups, Session session) throws Exception {
    List result = null;

    Query q = session.createQuery("from Calendar calendar order by calendar.id");

    Criteria criteria = session.createCriteria(Calendar.class);
    criteria.createCriteria("owningRoles").add(Expression.in("name", roles.toArray()));
    if (groups.size() > 0)
      criteria.createCriteria("owningGroups").add(Expression.in("name", groups.toArray()));
    criteria.addOrder(Order.asc("name"));

    // result = criteria.list();
    // return result;
    Set set = new LinkedHashSet();
    set.addAll(criteria.list());

    return set;
  }
 /** @see SerializedObjectDAO#getSerializedObjectByUuid(String) */
 public SerializedObject getSerializedObjectByUuid(String uuid) throws DAOException {
   SerializedObject ret = null;
   if (uuid != null) {
     Criteria c = sessionFactory.getCurrentSession().createCriteria(SerializedObject.class);
     c.add(Expression.eq("uuid", uuid));
     ret = (SerializedObject) c.uniqueResult();
   }
   return ret;
 }
 /** @see org.openmrs.api.db.LocationDAO#getAllLocationTags(boolean) */
 @SuppressWarnings("unchecked")
 public List<LocationTag> getAllLocationTags(boolean includeRetired) {
   Criteria criteria = sessionFactory.getCurrentSession().createCriteria(LocationTag.class);
   if (!includeRetired) {
     criteria.add(Expression.like("retired", false));
   }
   criteria.addOrder(Order.asc("name"));
   return criteria.list();
 }