/**
   * Método utilizado para criar o objeto Example. Este objeto é utilizado para realizar a busca por
   * exemplo.
   *
   * @param objeto sobre o qual o Example será criado
   * @return em objeto do tipo Example
   */
  public final Example criarExemplo(T objeto) {

    Example example = Example.create(objeto);
    example.enableLike(MatchMode.ANYWHERE);
    example.excludeZeroes();
    example.ignoreCase();

    return example;
  }
Пример #2
0
 @Override
 public List<E> getByExample(E exampleInstance, String[] excludeProperty) {
   Example example = Example.create(exampleInstance);
   if (excludeProperty != null) {
     for (String str : excludeProperty) {
       example.excludeProperty(str);
     }
   }
   return ht.findByExample(example);
 }
 @Override
 public List<Template> findAllByExample(Template exampleObject, List<String> excludedProperties) {
   Criteria criteriaQuery = getSession().createCriteria(getPersistentClass());
   Example example = Example.create(exampleObject);
   for (String excludeProperty : excludedProperties) {
     example.excludeProperty(excludeProperty);
   }
   criteriaQuery.add(example);
   return criteriaQuery.list();
 }
	@SuppressWarnings("unchecked")
	public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
		Criteria crit = getSession().createCriteria(getPersistentClass());
		Example example = Example.create(exampleInstance);
		for (String exclude : excludeProperty) {
			example.excludeProperty(exclude);
		}
		crit.add(example);
		return crit.list();
	}
 @SuppressWarnings("unchecked")
 public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
   DetachedCriteria crit = DetachedCriteria.forClass(persistentClass);
   Example example = Example.create(exampleInstance);
   for (String exclude : excludeProperty) {
     example.excludeProperty(exclude);
   }
   crit.add(example);
   return getHibernateTemplate().findByCriteria(crit);
 }
Пример #6
0
 /* (non-Javadoc)
  * @see cn.commonframework.util.BaseDAO#getAllByExample(java.lang.Object)
  */
 @SuppressWarnings("unchecked")
 @Override
 public List<Structure> getAllByExample(Structure structure) {
   DetachedCriteria criteria = DetachedCriteria.forClass(Structure.class);
   criteria.add(
       Example.create(structure).ignoreCase().enableLike(MatchMode.ANYWHERE).excludeZeroes());
   if (structure.getParentOrgan() != null) {
     criteria.createCriteria("parentOrgan").add(Example.create(structure.getParentOrgan()));
   }
   return this.getHibernateTemplate().findByCriteria(criteria);
 }
Пример #7
0
 @SuppressWarnings("unchecked")
 public List<T> findByExample(T exampleInstance, String[] excludeProperty) {
   String[] exclude = (excludeProperty != null) ? excludeProperty : excludeDefault;
   Criteria crit = getSession().createCriteria(persistentClass);
   Example example = Example.create(exampleInstance);
   example.enableLike();
   example.ignoreCase();
   for (String ex : exclude) {
     example.excludeProperty(ex);
   }
   crit.add(example);
   return crit.list();
 }
Пример #8
0
  @Override
  protected Criteria createCriteria(Board template) {
    Criteria criteria = super.createCriteria(template);
    if (template.getBoardDef() != null) {
      criteria
          .createCriteria(Board.PROPERTY_priceAware)
          .add(Example.create(template.getBoardDef()));
    }

    if (template.getTexture() != null) {
      criteria.createCriteria(Board.PROPERTY_priced).add(Example.create(template.getTexture()));
    }
    return criteria;
  }
Пример #9
0
  @SuppressWarnings("unchecked")
  public List<T> findByExample(
      T instance,
      Set<String> excludedProperties,
      Set<String> includedCollections,
      int fromRecord,
      int toRecord) {
    try {
      Example exampleInstance = create(instance);

      // Exclude the properties
      if (excludedProperties != null) {
        for (String excludedProperty : excludedProperties) {
          exampleInstance = exampleInstance.excludeProperty(excludedProperty);
        }
      }

      Criteria myCriteria =
          sessionFactory.getCurrentSession().createCriteria(clazz.getCanonicalName());

      if (includedCollections != null) {
        // Include the collections
        for (String includedCollection : includedCollections) {
          myCriteria.setFetchMode(includedCollection, FetchMode.JOIN);
        }
      }

      // set the LIMIT
      if (fromRecord >= 0 && toRecord >= 0) {
        if (fromRecord < toRecord) {
          myCriteria.setFirstResult(fromRecord);
          myCriteria.setMaxResults(toRecord - fromRecord);
        } else {
          myCriteria.setFirstResult(toRecord);
          myCriteria.setMaxResults(fromRecord - toRecord);
        }
      }

      // Only get distinct Root entities
      myCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

      // get the results
      List<T> results = (List<T>) myCriteria.add(exampleInstance).list();
      return results;
    } catch (RuntimeException re) {
      throw re;
    }
  }
Пример #10
0
 /**
  * Check if the item is accessible for the given User and session. It is if there is no lock or
  * the user owns the lock.
  *
  * @param item
  * @return
  */
 public boolean canAccess(User u, String sessionId, Lockable item) {
   boolean result = true;
   StatelessSession s = getSession();
   Transaction tx = s.beginTransaction();
   try {
     Lock example = createLock(item);
     Lock lock =
         (Lock)
             s.createCriteria(Lock.class)
                 .add(
                     Example.create(example)
                         .excludeProperty("httpSessionId")
                         .excludeProperty("userLogin")
                         .excludeProperty("name"))
                 .uniqueResult();
     tx.commit();
     if (lock != null) {
       if ((lock.getUserLogin().equals(u.getLogin()))
           && (lock.getHttpSessionId().equals(sessionId))) result = true;
       else result = false;
     }
   } catch (HibernateException he) {
     log.debug("Lock problem in canAccess");
     tx.rollback();
   }
   return result;
 }
Пример #11
0
  /**
   * Check if the item is locked. Return the Lock to check since when, what User etc. Return null if
   * there is no lock.
   *
   * @param item
   * @return
   */
  public Lock isLocked(Lockable item) {
    Lock result = null;
    StatelessSession s = getSession();
    Transaction tx = s.beginTransaction();
    try {
      Lock example = createLock(item);
      Lock lock =
          (Lock)
              s.createCriteria(Lock.class)
                  .add(
                      Example.create(example)
                          .excludeProperty("httpSessionId")
                          .excludeProperty("userLogin")
                          .excludeProperty("name"))
                  .uniqueResult();
      tx.commit();
      if (lock != null) result = lock;
    } catch (HibernateException he) {
      log.debug("lock not released");
      tx.rollback();
    } catch (Exception e) {
      // this throws more than hibernate exception
      log.debug("lock not released");
      tx.rollback();
    }

    return result;
  }
  /** 获得资源列表 */
  public List getResourceList(String ResourceType, String key) {
    // TODO Auto-generated method stub
    List<LabelValueBean> resourceList = new ArrayList<LabelValueBean>();
    try {
      ResourceInfo resource = new ResourceInfo();
      resource.setResourceType(ResourceType);
      DetachedCriteria dc = DetachedCriteria.forClass(ResourceInfo.class);
      dc.add(Example.create(resource));
      MyQuery myQuery = new MyQueryImpl();
      myQuery.setDetachedCriteria(dc);
      Object[] objs = this.dao.findEntity(myQuery);

      if (null != objs && 0 < objs.length) {
        ResourceInfo res = new ResourceInfo();
        for (int i = 0; i < objs.length; i++) {
          LabelValueBean resourceInfo = new LabelValueBean();
          res = (ResourceInfo) objs[i];
          resourceInfo.setValue(res.getId());
          resourceInfo.setLabel(res.getResourceName());
          resourceList.add(resourceInfo);
        }
      }
    } catch (Exception e) {
      logger.debug(e);
    }
    return resourceList;
  }
Пример #13
0
 public long countByDuplicate(Group record) {
   Group grp = new Group();
   grp.setId(record.getId());
   grp.setName(record.getName());
   DetachedCriteria dc = DetachedCriteria.forClass(Group.class).add(Example.create(grp));
   return groupMapper.count(dc);
 }
Пример #14
0
  public List regionsByExample(Countries countries) {

    Criteria cri = session.createCriteria(Countries.class);
    Example exam = Example.create(countries);
    cri.add(exam);
    return cri.list();
  }
Пример #15
0
  @SuppressWarnings("unchecked")
  public List<Dap> getDaps() {

    if (dapExample != null) {
      Example example =
          Example.create(dapExample).excludeFalse().ignoreCase().enableLike(MatchMode.ANYWHERE);
      return session.createCriteria(Dap.class).add(example).list();
    } else if (searchText != null && searchText.trim().length() > 0) {
      FullTextSession fullTextSession = Search.getFullTextSession(sessionManager.getSession());
      try {
        fullTextSession.createIndexer().startAndWait();
      } catch (java.lang.InterruptedException e) {
        logger.warn("Lucene Indexing was interrupted by something " + e);
      }

      QueryBuilder qb =
          fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(Dap.class).get();
      org.apache.lucene.search.Query luceneQuery =
          qb.keyword().onFields("name").matching(searchText).createQuery();

      return fullTextSession.createFullTextQuery(luceneQuery, Dap.class).list();
    } else {
      // default - unfiltered - all entitites list
      return session.createCriteria(Dap.class).list();
    }
  }
Пример #16
0
  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);
  }
Пример #17
0
  @SuppressWarnings("unchecked")
  public Collection<T> findByExample(T exampleInstance) {
    Criteria criteria =
        getSessionFactory().getCurrentSession().createCriteria(getPersistentClass());
    criteria.add(Example.create(exampleInstance));

    return criteria.list();
  }
Пример #18
0
  public List byExample(StaffRole staffRole) {

    Session session = HibernateTrain.getSession();
    Criteria cri = session.createCriteria(StaffRole.class);
    Example exam = Example.create(staffRole);
    cri.add(exam);
    return cri.list();
  }
Пример #19
0
 @SuppressWarnings("unchecked")
 @Override
 public List<T> findByExample(T bean) {
   /** 忽略大小写 */
   Example example = Example.create(bean).ignoreCase();
   Criteria criteria = getSession().createCriteria(bean.getClass()).add(example);
   return criteria.list();
 }
Пример #20
0
 /**
  * 查詢離校校生清單資料
  *
  * @param student tw.edu.chit.model.Graduate
  * @return java.util.List List of Graduate Objects
  */
 @SuppressWarnings("unchecked")
 public List<Graduate> getGraduatesBy(Graduate graduate) {
   Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
   return session
       .createCriteria(Graduate.class)
       .add(Example.create(graduate).enableLike(MatchMode.START))
       .addOrder(Order.asc("departClass"))
       .list();
 }
Пример #21
0
 /**
  * 查詢離職教職員工
  *
  * @param dempl
  * @return
  */
 @SuppressWarnings("unchecked")
 public List<DEmpl> findDEmplBy(DEmpl dempl) {
   Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
   return session
       .createCriteria(DEmpl.class)
       .add(Example.create(dempl).enableLike(MatchMode.START))
       .addOrder(Order.asc("idno"))
       .list();
 }
Пример #22
0
  @Override
  public int countByExample(final T exampleInstance) {
    Session session = (Session) getEntityManager().getDelegate();
    Criteria crit = session.createCriteria(getEntityClass());
    crit.setProjection(Projections.rowCount());
    crit.add(Example.create(exampleInstance));

    return (Integer) crit.list().get(0);
  }
Пример #23
0
 @Override
 public List<Dept> findDepts(Dept dept, boolean parentIsNull) {
   DetachedCriteria detachedCriteria = createDetachedCriteria();
   detachedCriteria.add(Example.create(dept));
   if (parentIsNull) {
     detachedCriteria.add(Restrictions.isNull("parent"));
   }
   return findDatas(detachedCriteria);
 }
Пример #24
0
 @SuppressWarnings("unchecked")
 public List<Contrato> findByExample(Contrato instance) {
   try {
     List<Contrato> results =
         getSession().createCriteria(LOCAL_VO + "Contrato").add(Example.create(instance)).list();
     return results;
   } catch (RuntimeException re) {
     throw re;
   }
 }
Пример #25
0
 public List findByExample(User instance) {
   log.debug("finding User instance by example");
   try {
     List results = getSession().createCriteria(User.class).add(Example.create(instance)).list();
     log.debug("find by example successful, result size: " + results.size());
     return results;
   } catch (RuntimeException re) {
     log.error("find by example failed", re);
     throw re;
   }
 }
Пример #26
0
  protected Criteria createExampleCriteria(T exampleInstance, Session sesion) {

    Criteria criteria = sesion.createCriteria(type);
    criteria.add(Example.create(exampleInstance));

    // Hibernate ignores fields that identifiers or are Entity types;
    // call addChildExampleCriteria to add these.
    addChildExampleCriteria(exampleInstance, criteria, sesion);

    return criteria;
  }
Пример #27
0
  @Override
  public List<AppTest> getSearch(AppTest appTest) throws Exception {
    Session session = (Session) em.getDelegate();

    Criteria criteria = session.createCriteria(AppTest.class);

    Example example =
        Example.create(appTest).excludeZeroes().ignoreCase().enableLike(MatchMode.ANYWHERE);

    criteria.add(example);
    return criteria.list();
  }
Пример #28
0
  @Test
  public void testCount() {
    User search = new User();
    search.setFirstName("first_name_page");
    search.setLastName("last_name_page");

    Example example = Example.create(search);
    DetachedCriteria dc = DetachedCriteria.forClass(User.class).add(example);

    Long count = userMapper.count(dc);
    assertEquals(Long.valueOf(3), count);
  }
Пример #29
0
 @SuppressWarnings("unchecked")
 public List<StatusCliente> findByExample(StatusCliente instance) {
   try {
     List<StatusCliente> results =
         getSession()
             .createCriteria(LOCAL_VO + "StatusCliente")
             .add(Example.create(instance))
             .list();
     return results;
   } catch (RuntimeException re) {
     throw re;
   }
 }
Пример #30
0
  /**
   * Create the search criteria for a {@link Translation}.
   *
   * @param translations the translation to add to the criteria
   * @param ignoreCase flag indicating if case should be ignored during search
   * @param matchMode flag indicating the type of string pattern matching
   * @return the additional search parameters for the {@link Translation} fields
   */
  private Conjunction createTranslationConditions(
      SortedSet<Translation> translations, final boolean ignoreCase, final MatchMode matchMode) {
    Conjunction conjunction = null;
    if (translations != null && !translations.isEmpty()) {
      final Translation translation = translations.first();

      Example criterionTranslation = Example.create(translation);
      criterionTranslation.enableLike(matchMode);
      if (ignoreCase) {
        criterionTranslation.ignoreCase();
      }

      conjunction = conjunction();
      conjunction.add(criterionTranslation);

      addBundleCriteria(conjunction, translation.getBundle());
      addCountryCriteria(conjunction, translation.getCountry());
      addLanguageCriteria(conjunction, translation.getLanguage());
    }

    return conjunction;
  }