@Override public <T> List<T> findByExample( final String entityName, final T exampleEntity, final int firstResult, final int maxResults) throws DataAccessException { Assert.notNull(exampleEntity, "Example entity must not be null"); return executeWithNativeSession(new HibernateCallback<List<T>>() { @Override @SuppressWarnings("unchecked") public List<T> doInHibernate(Session session) throws HibernateException { Criteria executableCriteria = (entityName != null ? session.createCriteria(entityName) : session.createCriteria(exampleEntity.getClass())); executableCriteria.add(Example.create(exampleEntity)); prepareCriteria(executableCriteria); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (maxResults > 0) { executableCriteria.setMaxResults(maxResults); } return executableCriteria.list(); } }); }
public <T> List<T> doFindByExample(final String entityName, final T exampleEntity, final int firstResult, final int maxResults) { if (exampleEntity == null) { throw new IllegalArgumentException("Example entity must not be null"); } Criteria executableCriteria = (entityName != null ? getSession().createCriteria(entityName) : getSession().createCriteria(exampleEntity.getClass())); executableCriteria.add(Example.create(exampleEntity)); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (maxResults > 0) { executableCriteria.setMaxResults(maxResults); } return executableCriteria.list(); }
public <T> List<T> findByExample(final String entityName, final T exampleEntity, final int firstResult, final int maxResults) { if (exampleEntity == null) { throw new IllegalArgumentException("Example entity must not be null"); } Criteria executableCriteria = (entityName != null ? getSession().createCriteria(entityName) : getSession().createCriteria(exampleEntity.getClass())); executableCriteria.add(Example.create(exampleEntity)); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (maxResults > 0) { executableCriteria.setMaxResults(maxResults); } return executableCriteria.list(); }
@Override public CatalogConvertor getByMarketApp(Session sess, String marketName, short catalog, int subCatalog) { Criteria cri = sess.createCriteria(CatalogConvertor.class); CatalogConvertor catalogConvertor = new CatalogConvertor(); catalogConvertor.setMarketName(marketName); catalogConvertor.setCatalog(catalog); catalogConvertor.setSubCatalog(subCatalog); Example example = Example.create(catalogConvertor); example.excludeZeroes(); cri.add(example); Object o = cri.uniqueResult(); if (o != null) { catalogConvertor = (CatalogConvertor) o; } return catalogConvertor; }
public List findByExample(Secuserrole instance) { Session session = getSession(); logger.debug("finding Secuserrole instance by example"); try { List results = session.createCriteria( "com.quatro.model.security.Secuserrole").add( Example.create(instance)).list(); logger.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { logger.error("find by example failed", re); throw re; } finally { this.releaseSession(session); } }
public List findByExample(SecProviderDao instance) { logger.debug("finding Provider instance by example"); Session session = getSession(); try { List results = session.createCriteria( "com.quatro.model.security.SecProvider").add( Example.create(instance)).list(); logger.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { logger.error("find by example failed", re); throw re; } finally { this.releaseSession(session); } }
@Test public void testQBE() { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); Topic topicExample = new Topic(); topicExample.setTitle("Category4%"); Example example = Example.create( topicExample).ignoreCase().enableLike(); Criteria criteria = session.createCriteria(Topic.class) .add(Restrictions.like("title", "%topic7")) .add(example) ; for (Object object : criteria.list()) { Topic topic = (Topic)object; System.out.println(topic); } }
public void testSimpleQBE() throws Exception { deleteData(); initData(); Session s = openSession(); Transaction t = s.beginTransaction(); Componentizable master = getMaster("hibernate", "open sourc%", "open source1"); Criteria crit = s.createCriteria(Componentizable.class); Example ex = Example.create(master).enableLike(); crit.add(ex); List result = crit.list(); assertNotNull(result); assertEquals(1, result.size()); t.commit(); s.close(); }
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(); }
@Override public Page<Taxon> searchByExample(Taxon example, boolean ignoreCase, boolean useLike) { Example criterion = Example.create(example); if(ignoreCase) { criterion.ignoreCase(); } if(useLike) { criterion.enableLike(); } Criteria criteria = getSession().createCriteria(Taxon.class); criteria.add(criterion); List<Taxon> results = (List<Taxon>) criteria.list(); Page<Taxon> page = new DefaultPageImpl<Taxon>(results.size(), null, null, results, null); return page; }
@SuppressWarnings("unchecked") @Override public List<T> findByExample(T exampleInstance, String... excludeProperty) { try { Criteria crit = getSession().createCriteria(getPersistentClass()); Example example = Example.create(exampleInstance); for (String exclude : excludeProperty) { example.excludeProperty(exclude); } crit.add(example); return crit.list(); } catch (Exception e) { // e.printStackTrace(); getTransaction().rollback(); return null; } }
/** * @Title: countByExample * @Description: 根据模型统计 * @param @param entityBean * @param @return * @return int */ public <T> int countByExample(final T obj) { return (Integer) getHibernateTemplate().executeWithNativeSession(new HibernateCallback<Integer>() { public Integer doInHibernate(Session s) throws HibernateException, SQLException { // 组装属性 Criteria criteria = s.createCriteria(obj.getClass()).setProjection(Projections.projectionList().add(Projections.rowCount())) .add(Example.create(obj)); if (getHibernateTemplate().isCacheQueries()) { criteria.setCacheable(true); if (getHibernateTemplate().getQueryCacheRegion() != null) criteria.setCacheRegion(getHibernateTemplate().getQueryCacheRegion()); } if (getHibernateTemplate().getFetchSize() > 0) criteria.setFetchSize(getHibernateTemplate().getFetchSize()); if (getHibernateTemplate().getMaxResults() > 0) criteria.setMaxResults(getHibernateTemplate().getMaxResults()); SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory()); return (Integer) criteria.uniqueResult(); } }); }
/** * Execute a query based on a given example entity object. * * @param entityName the name of the persistent entity * @param exampleEntity an instance of the desired entity, serving as example for "query-by-example" * @param firstResult the index of the first result object to be retrieved (numbered from 0) * @param maxResults the maximum number of result objects to retrieve (or <=0 for no limit) * @return a {@link List} containing 0 or more persistent instances * @throws org.springframework.dao.DataAccessException in case of Hibernate errors * @see org.hibernate.criterion.Example#create(Object) * @see org.hibernate.Criteria#setFirstResult(int) * @see org.hibernate.Criteria#setMaxResults(int) */ @SuppressWarnings("unchecked") @Override public List<Object> findByExample(final String entityName, final Object exampleEntity, final int firstResult, final int max) throws DataAccessException { Assert.notNull(exampleEntity, "Example entity must not be null"); return executeWithNativeSession(session -> { Criteria executableCriteria = (entityName != null ? session.createCriteria(entityName) : session.createCriteria(exampleEntity.getClass())); executableCriteria.add(Example.create(exampleEntity)); prepareCriteria(executableCriteria); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (max > 0) { executableCriteria.setMaxResults(max); } return executableCriteria.list(); }); }
private List<ExerciseGroup> findByExampleHbn(ExerciseGroup instance, Session session) { log.debug("finding ExerciseGroup instance by example"); try { if (session != null) { Criteria criteria = session.createCriteria("de.uniwue.info6.database.map.ExerciseGroup"); criteria.add(Example.create(instance)); if (instance.getScenario() != null) { criteria.createAlias("scenario", "sc") .add(Restrictions.eq("sc.id", instance.getScenario().getId())); } @SuppressWarnings("unchecked") List<ExerciseGroup> results = criteria.list(); log.debug("find by example successful, result size: " + results.size()); return results; } return null; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } }
private List<SolutionQuery> findByExampleHbn(SolutionQuery instance, Session session) { log.debug("finding SolutionQuery instance by example"); try { Criteria criteria = session.createCriteria("de.uniwue.info6.database.map.SolutionQuery"); criteria.add(Example.create(instance)); if (instance.getExercise() != null) { criteria.createAlias("exercise", "e").add(Restrictions.eq("e.id", instance.getExercise().getId())); } @SuppressWarnings("unchecked") List<SolutionQuery> results = criteria.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; } }
public List findByExample( final String entityName, final Object exampleEntity, final int firstResult, final int maxResults) throws DataAccessException { Assert.notNull(exampleEntity, "Example entity must not be null"); return executeWithNativeSession(new HibernateCallback<List>() { public List doInHibernate(Session session) throws HibernateException { Criteria executableCriteria = (entityName != null ? session.createCriteria(entityName) : session.createCriteria(exampleEntity.getClass())); executableCriteria.add(Example.create(exampleEntity)); prepareCriteria(executableCriteria); if (firstResult >= 0) { executableCriteria.setFirstResult(firstResult); } if (maxResults > 0) { executableCriteria.setMaxResults(maxResults); } return executableCriteria.list(); } }); }
public List<Course> getCoursesByAdvancedRule(String name, String professorName, Date initialDate, Date finalDate){ Course course = new Course(); course.setName(name); course.setInitialCourseDate(initialDate); course.setFinalCourseDate(finalDate); Example courseExample = Example.create(course) .setPropertySelector(new NotNullOrBlankPropertySelector()) //elimina da consulta as propriedades que s�o nulas ou vazias .excludeZeroes() .ignoreCase() .enableLike(MatchMode.ANYWHERE); Criteria crit = getSession().createCriteria(Course.class); crit.add(courseExample) .createCriteria("professor") .add(Restrictions.ilike("name", professorName, MatchMode.ANYWHERE)); List<Course> results = crit.list(); return results; }
/** * @param <T> * @param exampleInstance * @param excludeZeros * @param excludeProperty * @return * @see edu.utah.further.core.api.data.Dao#findByExample(edu.utah.further.core.api.data.PersistentEntity, * boolean, java.lang.String[]) */ @Override public <T extends PersistentEntity<?>> List<T> findByExample(final T exampleInstance, final boolean excludeZeros, final String... excludeProperty) { final GenericCriteria crit = createCriteria(exampleInstance.getClass()); final Example example = Example.create(exampleInstance); if (excludeZeros) { example.excludeZeroes(); } for (final String exclude : excludeProperty) { example.excludeProperty(exclude); } crit.add(example); return getNullSafeList(crit.<T> list()); }
/** * @see GenericDao#findByExample(Object, String...) */ @SuppressWarnings("unchecked") public List<T> findByExample(T exampleInstance, String... excludeProperty) throws DataAccessException { try { Criteria crit = getSession().createCriteria(getPersistentClass()); Example example = Example.create(exampleInstance); for (String exclude : excludeProperty) { example.excludeProperty(exclude); } crit.add(example); return crit.list(); } catch (HibernateException e) { throw SessionFactoryUtils.convertHibernateAccessException(e); } }
@Override public Connection getConnection(PatientSimilarityView patientPair) { Session session = this.sessionFactory.getSessionFactory().openSession(); Criteria c = session.createCriteria(Connection.class); Connection connection = new Connection(this.publicPatientSimilarityViewFactory.convert(patientPair)); c.add(Example.create(connection).excludeProperty("id")); @SuppressWarnings("unchecked") List<Connection> foundEntries = c.list(); if (foundEntries.isEmpty()) { Transaction t = session.beginTransaction(); t.begin(); session.save(connection); t.commit(); return connection; } return foundEntries.get(0); }
/** * Metodo para listar objetos semelhantes ao Object example * * @param exemplo * : objeto Example * @param isEnableLike * : True se � para ativar o "Like" na consulta, false para * desativar * @param isIgnoreCase * : True se � para ignorar mai�sculas e min�sculas na consulta, * false para case sensitive * */ @Transactional(readOnly = true, propagation = Propagation.REQUIRED) public List getPeloExemplo(Object example, boolean isEnableLike, boolean isIgnoreCase) { Criteria criteria = this.sessionFactory.getCurrentSession() .createCriteria(example.getClass()); Example sample = Example.create(example); if (isEnableLike) sample.enableLike(MatchMode.ANYWHERE); if (isIgnoreCase) sample.ignoreCase(); sample.excludeZeroes(); criteria.add(sample); return criteria.list(); }
/** * * @param clinicalIds ids * @param target target */ public void saveLoadLabStatus(List<Long> clinicalIds, String target) { Session session = getSession(); Transaction tran = session.beginTransaction(); for (Long id : clinicalIds) { Criteria labCrit = session.createCriteria(LoadLabStatus.class); LoadLabStatus llstatus = new LoadLabStatus(); llstatus.setClinicalResultId(id); labCrit.add(Example.create(llstatus)); if (labCrit.list().isEmpty()) { if (LVConstants.CAAERS.equals(target)) { llstatus.setAeIndicator("true"); llstatus.setAeSentDate(new Date()); } else { llstatus.setCdmsIndicator("true"); llstatus.setCdmsDate(new Date()); } session.save(llstatus); } } updateLabStatus(clinicalIds, target, session); tran.commit(); }
/** * Returns a count of the number of saved queries for a user * * @param userName * @throws Exception */ @Transactional(propagation=Propagation.REQUIRED) public int getSavedQueryCount(String userName) throws DataAccessException { Integer count = null; // Create criteria to get the count of saved queries SavedQuery sq = new SavedQuery(); sq.setUserId(getUser(userName).getUserId()); sq.setActive(true); DetachedCriteria crit = DetachedCriteria.forClass(SavedQuery.class); crit.add(Example.create(sq)); // Need to do distinct because the query will // bring back one row for each query attribute crit.setProjection(Projections.countDistinct("id")); List results = getHibernateTemplate().findByCriteria(crit); if(results.size()>0) { count = (Integer) results.get(0); } return (count != null) ? count : 0; }
/** * Retrieves a list of active saved queries for a user * * @param username - login id of the user * @return list of active saved queries for the user * @throws Exception */ @Transactional(propagation=Propagation.REQUIRED) public List<SavedQueryDTO> retrieveSavedQueries(String username) throws DataAccessException { // Create criteria to get all active saved queries // for a user SavedQuery sq = new SavedQuery(); sq.setActive(true); sq.setUserId(getUser(username).getUserId()); DetachedCriteria crit = DetachedCriteria.forClass(SavedQuery.class); crit.add(Example.create(sq)); // Set fetch modes so that these will be included in the same query crit.setFetchMode("savedQueryAttributes", FetchMode.JOIN); crit.setFetchMode("lastExecuteDate", FetchMode.JOIN); // Need to do distinct because query will actually return // one row for each query criterion, resulting in duplicate rows crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return this.populateSavedQueryDTOs(getHibernateTemplate().findByCriteria(crit)); }
/** * Retrieves a list of active saved queries for a user * * @param username - login id of the user * @return list of active saved queries for the user * @throws Exception */ @Transactional(propagation=Propagation.REQUIRED) public List<SavedQueryDTO> retrieveAllSavedQueries() throws DataAccessException { // Create criteria to get all active saved queries // for a user SavedQuery sq = new SavedQuery(); sq.setActive(true); DetachedCriteria crit = DetachedCriteria.forClass(SavedQuery.class); crit.add(Example.create(sq)); // Set fetch modes so that these will be included in the same query crit.setFetchMode("savedQueryAttributes", FetchMode.JOIN); crit.setFetchMode("lastExecuteDate", FetchMode.JOIN); //crit.setFetchMode("user", FetchMode.JOIN); // Need to do distinct because query will actually return // one row for each query criterion, resulting in duplicate rows crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); return this.populateSavedQueryDTOs(getHibernateTemplate().findByCriteria(crit)); }
/** * Convenience method to look up a user object based on the login name * * @param loginName - user's login name * @param dataAccess - access to Hibernate */ private NCIAUser getUser(String loginName) { // Create the example criteria and run the query NCIAUser user = new NCIAUser(); user.setLoginName(loginName); DetachedCriteria crit = DetachedCriteria.forClass(NCIAUser.class); crit.add(Example.create(user)); List result = getHibernateTemplate().findByCriteria(crit); if ((result != null) && (result.size() > 0)) { return (NCIAUser) result.get(0); } else { throw new RuntimeException("User not found in getUser():"+loginName); } }
@Override public List<?> search(Admin admin) { Session session = sessionFactory.getCurrentSession(); Criteria c = session.createCriteria(Admin.class); // 创建示例条件 Example example = Example.create(admin); c.add(example); return c.list(); }
@Override public boolean allowAccess(String marketName, String key) { Criteria cri = getSession().createCriteria(Market.class); Market entity = new Market(); entity.setMarketName(marketName); entity.setAllowAccessKey(key); Example exa = Example.create(entity); exa.excludeZeroes(); cri.add(exa); return cri.uniqueResult() != null; }
public List<T> findOrderedByExample( final T p_exampleInstance, final String[] sort, final boolean asc) { return findOrderedByCriteria( sort, asc, Example.create(p_exampleInstance)); }
public List<T> findPagedAndOrderedByExample( final T p_exampleInstance, final String[] sort, final boolean asc, final int firstRow, final int maxResults) { return findPagedAndOrderedByCriteria( firstRow, maxResults, sort, asc, Example.create(p_exampleInstance)); }
public List<Users> search(Users users) { Object execute = super.getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(Session session) throws HibernateException { Criteria criteria = session.createCriteria(Users.class); if(users != null) criteria.add(Example.create(users)); return criteria.list(); } }); return (List<Users>) execute; }
@Override public List<R> getByExample(final R example) { final Criteria criteria = getSession().createCriteria(entityClass); criteria.add(Example.create(example)); final List<R> list = criteria.list(); return list; }
@Override public R getUniqueByExample(final R example) { final Criteria criteria = getSession().createCriteria(entityClass); criteria.add(Example.create(example)); R result = (R) criteria.uniqueResult(); return result; }