List of usage examples for org.hibernate Criteria setProjection
public Criteria setProjection(Projection projection);
From source file:com.gisgraphy.hibernate.criterion.ProjectionOrderTest.java
License:Open Source License
@SuppressWarnings("unchecked") @Test// ww w .jav a 2 s.c om public void testProjectionOrderShouldSortAscByDefault() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as("featureId"); testCriteria.setProjection(projection).addOrder(new ProjectionOrder("featureId")) .setResultTransformer(Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("1", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("3", cities.get(2).getFeatureId().toString()); }
From source file:com.gisgraphy.hibernate.criterion.ProjectionOrderTest.java
License:Open Source License
@SuppressWarnings("unchecked") @Test/*w ww .j av a 2 s. c om*/ public void testProjectionOrderShouldSortDesc() { final City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); City p2 = GisgraphyTestHelper.createCity("bordeaux", 44.83333F, -0.56667F, 3L); City p3 = GisgraphyTestHelper.createCity("goussainville", 49.01667F, 2.46667F, 2L); this.cityDao.save(p1); this.cityDao.save(p2); this.cityDao.save(p3); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); Projection projection = Projections.property("featureId").as("featureId"); testCriteria.setProjection(projection).addOrder(new ProjectionOrder("featureId", false)) .setResultTransformer(Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } }; List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback); assertEquals(3, cities.size()); assertEquals("3", cities.get(0).getFeatureId().toString()); assertEquals("2", cities.get(1).getFeatureId().toString()); assertEquals("1", cities.get(2).getFeatureId().toString()); }
From source file:com.gisgraphy.hibernate.projection.ProjectionBeanTest.java
License:Open Source License
@SuppressWarnings("unchecked") @Test//from w w w . j av a 2 s . c o m public void testPropertiesList() { City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); this.cityDao.save(p1); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(City.class); List<String> fieldList = new ArrayList<String>(); fieldList.add("name"); fieldList.add("featureId"); ProjectionList projection = ProjectionBean.fieldList(fieldList, true); testCriteria.setProjection(projection); testCriteria.setResultTransformer(Transformers.aliasToBean(City.class)); List<City> results = testCriteria.list(); return results; } }; List<City> cities = (List<City>) testDao.testCallback(hibernateCallback); assertEquals(1, cities.size()); assertEquals("paris", cities.get(0).getName()); assertEquals("1", cities.get(0).getFeatureId() + ""); }
From source file:com.gisgraphy.hibernate.projection.ProjectionBeanTest.java
License:Open Source License
@SuppressWarnings("unchecked") @Test// w w w . j a v a2 s . com public void testBeanFieldList() { City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); this.cityDao.save(p1); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { try { Criteria testCriteria = session.createCriteria(City.class); String[] ignoreFields = { "distance" }; ProjectionList projection = ProjectionBean.beanFieldList(_CityDTO.class, ignoreFields, true); testCriteria.setProjection(projection); testCriteria.setResultTransformer(Transformers.aliasToBean(_CityDTO.class)); List<_CityDTO> results = testCriteria.list(); return results; } catch (HibernateException e) { fail("An exception has occured : maybe ignoreFields are not taken into account if the error is 'could not resolve property: distance... :" + e); throw e; } } }; List<_CityDTO> cities = (List<_CityDTO>) testDao.testCallback(hibernateCallback); assertEquals(1, cities.size()); assertEquals("paris", cities.get(0).getName()); assertEquals("1", cities.get(0).getFeatureId() + ""); }
From source file:com.gisgraphy.hibernate.projection.ProjectionBeanTest.java
License:Open Source License
@SuppressWarnings("unchecked") public void testBeanFieldListWithOutAutoAliasing() { City p1 = GisgraphyTestHelper.createCity("paris", 48.86667F, 2.3333F, 1L); this.cityDao.save(p1); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { try { Criteria testCriteria = session.createCriteria(City.class); String[] ignoreFields = { "distance" }; ProjectionList projection = ProjectionBean.beanFieldList(_CityDTO.class, ignoreFields, false); testCriteria.setProjection(projection); testCriteria.add(Restrictions.eq("name", "paris")); List<Object[]> results = testCriteria.list(); return results; } catch (HibernateException e) { fail("An exception has occured : there is maybe a bug with autoaliasing" + e); throw e; }/* ww w .j a v a2s. c o m*/ } }; List<Object[]> cities = (List<Object[]>) testDao.testCallback(hibernateCallback); assertEquals(1, cities.size()); assertEquals(1L, cities.get(0)[0]); }
From source file:com.gisgraphy.hibernate.projection.SpatialProjectionTest.java
License:Open Source License
@SuppressWarnings("unchecked") @Test//w w w .ja v a2 s. co m public void testdistance_pointToLine() { LineString shape = GeolocHelper.createLineString("LINESTRING (6.9416088 50.9154239,6.9410001 50.9154734)"); OpenStreetMap streetOSM = GisgraphyTestHelper.createOpenStreetMapForPeterMartinStreet(); streetOSM.setShape(shape); openStreetMapDao.save(streetOSM); assertNotNull(openStreetMapDao.get(streetOSM.getId())); final Point p1 = GeolocHelper.createPoint(6.9412748F, 50.9155829F); HibernateCallback hibernateCallback = new HibernateCallback() { public Object doInHibernate(Session session) throws PersistenceException { Criteria testCriteria = session.createCriteria(OpenStreetMap.class); ProjectionList projection = Projections.projectionList() .add(Projections.property("name").as("name")).add(SpatialProjection .distance_pointToLine(p1, OpenStreetMap.SHAPE_COLUMN_NAME).as("distance")) .add(Projections.property("shape").as("shape")); // remove the from point testCriteria.setProjection(projection); testCriteria.setResultTransformer(Transformers.aliasToBean(_OpenstreetmapDTO.class)); List<_OpenstreetmapDTO> results = testCriteria.list(); return results; } }; List<_OpenstreetmapDTO> streets = (List<_OpenstreetmapDTO>) testDao.testCallback(hibernateCallback); assertEquals(1, streets.size()); Double calculatedDist = 14.76D; Double retrieveDistance = streets.get(0).getDistance(); double percent = (Math.abs(calculatedDist - retrieveDistance) * 100) / Math.min(retrieveDistance, calculatedDist); assertTrue("There is more than one percent of error beetween the calculated distance (" + calculatedDist + ") and the retrieved one (" + retrieveDistance + ")", percent < 1); }
From source file:com.griffinslogistics.db.helpers.BooksHelper.java
public List<BookModel> getBookModelsByTransportation(Transportation transportation) { logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation started", CLASS_NAME); List<BookModel> resultList = new ArrayList<BookModel>(); this.session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = this.session.beginTransaction(); try {/*from w w w. j a v a 2 s . co m*/ Criteria criteria = this.session.createCriteria(Book.class); criteria.add(Restrictions.eq("transportation", transportation)); criteria.setProjection( Projections.projectionList().add(Projections.groupProperty("bookNumber"), "bookNumber") .add(Projections.property("title"), "title")) .setResultTransformer(Transformers.aliasToBean(BookModel.class)); resultList = criteria.list(); Collections.reverse(resultList); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); logger.log(Level.SEVERE, e.getMessage()); } finally { this.session.close(); logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation finished", CLASS_NAME); } return resultList; }
From source file:com.hazelcast.hibernate.app.Executor.java
License:Open Source License
public void execute() throws Exception { CountDownLatch latch = new CountDownLatch(1000); int count;/*w ww . j av a 2s .c om*/ Session session = sessionFactory.openSession(); try { Criteria criteria = session.createCriteria(DummyEntity.class); criteria.setProjection(Projections.rowCount()); count = ((Long) criteria.uniqueResult()).intValue(); } finally { session.close(); } if (count == 0) { count = 200000; insertDummyEntities(count, 100); } try { for (int i = 0; i < latch.getCount(); i++) { executorService.submit(new Task(i, sessionFactory, 1000, latch)); } latch.await(1, TimeUnit.DAYS); } finally { executorService.shutdown(); } }
From source file:com.heimaide.server.common.persistence.BaseDao.java
License:Open Source License
/** * //from ww w .j av a2 s. c om * * @param detachedCriteria * @return */ @SuppressWarnings("rawtypes") public long count(DetachedCriteria detachedCriteria) { Criteria criteria = detachedCriteria.getExecutableCriteria(getSession()); long totalCount = 0; try { // Get orders Field field = CriteriaImpl.class.getDeclaredField("orderEntries"); field.setAccessible(true); List orderEntrys = (List) field.get(criteria); // Remove orders field.set(criteria, new ArrayList()); // Get count criteria.setProjection(Projections.rowCount()); totalCount = Long.valueOf(criteria.uniqueResult().toString()); // Clean count criteria.setProjection(null); // Restore orders field.set(criteria, orderEntrys); } catch (NoSuchFieldException e) { logger.error("BaseDao:count error:" + Exceptions.getStackMsg(e)); } catch (IllegalAccessException e) { logger.error("BaseDao:count error:" + Exceptions.getStackMsg(e)); } return totalCount; }
From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java
License:Apache License
/** * Initializes a Criteria Query./*from w w w .j a v a2 s .co m*/ * Mandatory Attributes:<ul> * <li><b>name</b>: The unqualified class name driving the criteria query.</li> * </ul> * Optional Attributes:<ul> * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li> * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li> * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li> * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li> * <li><b>cacheMode</b>: The cache options for the queried objects.</li> * <li><b>flushMode</b>: The session flush options.</li> * <li><b>fetchMode</b>: The collection fetch options for the query.</li> * <li><b>lockMode</b>: The row lock options for the queried rows.</li> * <li><b>timeOut</b>: The query timeout option.</li> * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li> * </ul> * @param attrs The attributes of the processed node. * @return An appended or new CriteriaSpecification * @throws SAXException */ protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException { if (inDetached) { return criteriaStack.peek(); } String name = attrs.getValue("name"); String prefix = attrs.getValue("prefix"); if (prefix != null) { className = prefix + "." + name; } else { className = name; } String maxSize = attrs.getValue("maxSize"); String fetchSize = attrs.getValue("fetchSize"); String firstResult = attrs.getValue("firstResult"); String cacheEnabled = attrs.getValue("cacheEnabled"); String cacheMode = attrs.getValue("cacheMode"); String flushMode = attrs.getValue("flushMode"); String fetchMode = attrs.getValue("fetchMode"); String lockMode = attrs.getValue("lockMode"); String timeOut = attrs.getValue("timeOut"); String rowCountOnly = attrs.getValue("rowCountOnly"); Criteria newCriteria = null; try { if (criteriaStack.size() == 0) { newCriteria = session.createCriteria(className); } else { newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className); } criteriaStack.push(newCriteria); if ("true".equalsIgnoreCase(rowCountOnly)) { newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount()) ); setRowCountOnly(true); } if (maxSize != null && isRowCountOnly() == false) { newCriteria.setMaxResults(Integer.parseInt(maxSize)); } if (fetchSize != null && isRowCountOnly() == false) { newCriteria.setFetchSize(Integer.parseInt(fetchSize)); } if (firstResult != null && isRowCountOnly() == false) { newCriteria.setFirstResult(Integer.parseInt(firstResult)); } if (timeOut != null) { newCriteria.setTimeout(Integer.parseInt(timeOut)); } if ("true".equalsIgnoreCase(cacheEnabled)) { newCriteria.setCacheable(true); } else if ("false".equalsIgnoreCase(cacheEnabled)) { newCriteria.setCacheable(false); } if (fetchMode != null && fetchMode.length() > 0) { if ("JOIN".equalsIgnoreCase(fetchMode)) { newCriteria.setFetchMode(name, FetchMode.JOIN); } else if ("SELECT".equalsIgnoreCase(fetchMode)) { newCriteria.setFetchMode(name, FetchMode.SELECT); } else { newCriteria.setFetchMode(name, FetchMode.DEFAULT); } } else { newCriteria.setFetchMode(name, FetchMode.DEFAULT); } if (cacheMode != null && cacheMode.length() > 0) { if ("GET".equalsIgnoreCase(cacheMode)) { newCriteria.setCacheMode(CacheMode.GET); } else if ("IGNORE".equalsIgnoreCase(cacheMode)) { newCriteria.setCacheMode(CacheMode.IGNORE); } else if ("NORMAL".equalsIgnoreCase(cacheMode)) { newCriteria.setCacheMode(CacheMode.NORMAL); } else if ("PUT".equalsIgnoreCase(cacheMode)) { newCriteria.setCacheMode(CacheMode.PUT); } else if ("REFRESH".equalsIgnoreCase(cacheMode)) { newCriteria.setCacheMode(CacheMode.REFRESH); } else { newCriteria.setCacheMode(CacheMode.NORMAL); } } if (lockMode != null && lockMode.length() > 0) { if ("NONE".equalsIgnoreCase(lockMode)) { newCriteria.setLockMode(LockMode.NONE); } else if ("READ".equalsIgnoreCase(lockMode)) { newCriteria.setLockMode(LockMode.READ); } else if ("UPGRADE".equalsIgnoreCase(lockMode)) { newCriteria.setLockMode(LockMode.UPGRADE); } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) { newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT); } else if ("WRITE".equalsIgnoreCase(lockMode)) { newCriteria.setLockMode(LockMode.WRITE); } else { throw new SAXException("lockMode[" + lockMode + "] Not Recognized"); } } if (flushMode != null && flushMode.length() > 0) { if ("ALWAYS".equalsIgnoreCase(flushMode)) { newCriteria.setFlushMode(FlushMode.ALWAYS); } else if ("AUTO".equalsIgnoreCase(flushMode)) { newCriteria.setFlushMode(FlushMode.AUTO); } else if ("COMMIT".equalsIgnoreCase(flushMode)) { newCriteria.setFlushMode(FlushMode.COMMIT); } else if ("NEVER".equalsIgnoreCase(flushMode)) { // NEVER is deprecated, so we won't throw an exception but we'll ignore it. } else { throw new SAXException("flushMode[" + flushMode + "] Not Recognized"); } } return newCriteria; } catch (Exception e) { throw new SAXException("Unable to configure class " + className, e); } }