List of usage examples for org.hibernate Session getSessionFactory
SessionFactory getSessionFactory();
From source file:org.medici.bia.dao.JpaDao.java
License:Open Source License
/** * // w ww.j a v a 2s.co m * @throws PersistenceException */ public void generateIndex() throws PersistenceException { try { EntityManager entityManager = getEntityManager(); Session session = ((HibernateEntityManager) entityManager).getSession(); session = session.getSessionFactory().openSession(); FullTextSession fullTextSession = Search.getFullTextSession(session); fullTextSession.createIndexer(entityClass).batchSizeToLoadObjects(30).threadsForSubsequentFetching(8) .threadsToLoadObjects(4).threadsForIndexWriter(3).cacheMode(CacheMode.IGNORE).startAndWait(); } catch (Throwable throwable) { logger.error(throwable); } }
From source file:org.medici.bia.dao.JpaDao.java
License:Open Source License
/** * //from ww w .jav a 2 s. c o m */ public void optimizeIndex() throws PersistenceException { Session session = null; FullTextSession fullTextSession = null; ScrollableResults results = null; try { EntityManager entityManager = getEntityManager(); session = ((HibernateEntityManager) entityManager).getSession(); session = session.getSessionFactory().openSession(); fullTextSession = org.hibernate.search.Search.getFullTextSession(session); logger.info("Initiating Lucene Index Optimze..."); SearchFactory searchFactory = fullTextSession.getSearchFactory(); searchFactory.optimize(entityClass); logger.info("Finished Lucene Index Optimze"); } catch (Throwable throwable) { logger.error(throwable); } finally { if (results != null) { results.close(); } if (fullTextSession.isOpen()) { fullTextSession.close(); } if (session.isOpen()) { session.close(); } } }
From source file:org.medici.bia.dao.JpaDao.java
License:Open Source License
/** * //from w w w . ja va 2s. com * @param fromDate * @throws PersistenceException */ public void updateIndex(Date fromDate) throws PersistenceException { Session session = null; FullTextSession fullTextSession = null; ScrollableResults results = null; try { EntityManager entityManager = getEntityManager(); session = ((HibernateEntityManager) entityManager).getSession(); session = session.getSessionFactory().openSession(); fullTextSession = org.hibernate.search.Search.getFullTextSession(session); Query queryTotal = entityManager .createQuery("SELECT count(*) FROM " + entityClass + " where lastUpdate>=:lastUpdate"); queryTotal.setParameter("lastUpdate", fromDate); Long total = (Long) queryTotal.getSingleResult(); logger.info("Total Entities to be updated : " + total); if (total > 0) { Integer numberOfElements = 50; Integer numberOfElementsBeforeGC = 1000; org.hibernate.Query query = session .createQuery("FROM " + entityClass + " where lastUpdate>=:lastUpdate"); query.setParameter("lastUpdate", fromDate); Transaction tx = fullTextSession.beginTransaction(); query.setReadOnly(true); query.setLockMode("a", LockMode.NONE); results = query.scroll(ScrollMode.FORWARD_ONLY); Integer resultNumber = 0; while (results.next()) { Object entityClass = (Object) results.get(0); fullTextSession.delete(entityClass); fullTextSession.index(entityClass); resultNumber++; if (resultNumber % numberOfElements == 0) { flushingFullTextSession(total, resultNumber, fullTextSession); } if (resultNumber % numberOfElementsBeforeGC == 0) { System.gc(); logger.info("Invoked Garbage collector to prevent OutOfMemory Errors"); } } flushingFullTextSession(total, resultNumber, fullTextSession); tx.commit(); logger.info("Initiating Lucene Index Optimze..."); SearchFactory searchFactory = fullTextSession.getSearchFactory(); searchFactory.optimize(entityClass); logger.info("Finished Lucene Index Optimze"); } else { logger.info("No Entities found to be indexed."); } logger.info("Indexing documents terminated without errors."); } catch (Throwable throwable) { logger.error(throwable); } finally { if (results != null) { results.close(); } if (fullTextSession.isOpen()) { fullTextSession.close(); } if (session.isOpen()) { session.close(); } } }
From source file:org.n52.sos.ds.hibernate.dao.AbstractObservationDAO.java
License:Open Source License
public SosEnvelope getSpatialFilteringProfileEnvelopeForOfferingId(String offeringID, Session session) throws OwsExceptionReport { try {// ww w . j av a 2 s.co m // XXX workaround for Hibernate Spatial's lack of support for // GeoDB's extent aggregate see // http://www.hibernatespatial.org/pipermail/hibernatespatial-users/2013-August/000876.html Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect(); if (GeometryHandler.getInstance().isSpatialDatasource() && HibernateHelper.supportsFunction(dialect, HibernateConstants.FUNC_EXTENT)) { Criteria criteria = getDefaultObservationInfoCriteria(session); criteria.setProjection(SpatialProjections.extent(AbstractObservationTime.SAMPLING_GEOMETRY)); criteria.createCriteria(AbstractObservation.OFFERINGS) .add(Restrictions.eq(Offering.IDENTIFIER, offeringID)); LOGGER.debug("QUERY getSpatialFilteringProfileEnvelopeForOfferingId(offeringID): {}", HibernateHelper.getSqlString(criteria)); Geometry geom = (Geometry) criteria.uniqueResult(); geom = GeometryHandler.getInstance().switchCoordinateAxisFromToDatasourceIfNeeded(geom); if (geom != null) { return new SosEnvelope(geom.getEnvelopeInternal(), GeometryHandler.getInstance().getStorageEPSG()); } } else { final Envelope envelope = new Envelope(); Criteria criteria = getDefaultObservationInfoCriteria(session); criteria.createCriteria(AbstractObservation.OFFERINGS) .add(Restrictions.eq(Offering.IDENTIFIER, offeringID)); LOGGER.debug("QUERY getSpatialFilteringProfileEnvelopeForOfferingId(offeringID): {}", HibernateHelper.getSqlString(criteria)); @SuppressWarnings("unchecked") final List<AbstractObservationTime> observationTimes = criteria.list(); if (CollectionHelper.isNotEmpty(observationTimes)) { for (final AbstractObservationTime observationTime : observationTimes) { if (observationTime.hasSamplingGeometry()) { final Geometry geom = observationTime.getSamplingGeometry(); if (geom != null && geom.getEnvelopeInternal() != null) { envelope.expandToInclude(geom.getEnvelopeInternal()); } } } if (!envelope.isNull()) { return new SosEnvelope(envelope, GeometryHandler.getInstance().getStorageEPSG()); } } } } catch (final HibernateException he) { throw new NoApplicableCodeException().causedBy(he) .withMessage("Exception thrown while requesting feature envelope for observation ids"); } return null; }
From source file:org.n52.sos.ds.hibernate.dao.AbstractSpatialFilteringProfileDAO.java
License:Open Source License
/** * Get the Capabilities envelope for offering from Spatial Filtering Profile * /*from w w w . j a va2 s . c om*/ * @param clazz * Entity to create Criteria for * @param offeringID * Offering identifier * @param session * Hibernate session * @return Envelope * @throws OwsExceptionReport * If coordinate switching fails */ @SuppressWarnings("rawtypes") protected SosEnvelope getEnvelopeForOfferingId(Class clazz, String offeringID, Session session) throws OwsExceptionReport { try { // XXX workaround for Hibernate Spatial's lack of support for // GeoDB's extent aggregate see // http://www.hibernatespatial.org/pipermail/hibernatespatial-users/2013-August/000876.html Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect(); if (GeometryHandler.getInstance().isSpatialDatasource() && HibernateHelper.supportsFunction(dialect, HibernateConstants.FUNC_EXTENT)) { Criteria criteria = session.createCriteria(clazz); criteria.setProjection(SpatialProjections.extent(FeatureOfInterest.GEOMETRY)); Criteria createCriteria = criteria.createCriteria(AbstractSpatialFilteringProfile.OBSERVATION); createCriteria.createCriteria(AbstractObservation.OFFERINGS) .add(Restrictions.eq(Offering.IDENTIFIER, offeringID)); LOGGER.debug("QUERY getEnvelopeForOfferingId(offeringID): {}", HibernateHelper.getSqlString(criteria)); Geometry geom = (Geometry) criteria.uniqueResult(); if (geom != null) { int srid = geom.getSRID() > 0 ? geom.getSRID() : GeometryHandler.getInstance().getStorageEPSG(); geom.setSRID(srid); return new SosEnvelope(GeometryHandler.getInstance() .switchCoordinateAxisFromToDatasourceIfNeeded(geom).getEnvelopeInternal(), srid); } } else { final Envelope envelope = new Envelope(); Criteria criteria = session.createCriteria(getSpatialFilteringProfileImpl().getClass()); Criteria createCriteria = criteria.createCriteria(AbstractSpatialFilteringProfile.OBSERVATION); createCriteria.createCriteria(AbstractObservation.OFFERINGS) .add(Restrictions.eq(Offering.IDENTIFIER, offeringID)); LOGGER.debug("QUERY getEnvelopeForOfferingId(offeringID): {}", HibernateHelper.getSqlString(criteria)); @SuppressWarnings("unchecked") final List<AbstractSpatialFilteringProfile> spatialFilteringProfiles = criteria.list(); if (CollectionHelper.isNotEmpty(spatialFilteringProfiles)) { for (final AbstractSpatialFilteringProfile spatialFilteringProfile : spatialFilteringProfiles) { try { final Geometry geom = getGeomtery(spatialFilteringProfile); if (geom != null && geom.getEnvelopeInternal() != null) { envelope.expandToInclude(geom.getEnvelopeInternal()); } } catch (final OwsExceptionReport owse) { LOGGER.warn(String.format("Error while adding '%s' to envelope!", spatialFilteringProfile.getSpatialFilteringProfileId()), owse); } } if (!envelope.isNull()) { return new SosEnvelope(envelope, GeometryHandler.getInstance().getStorageEPSG()); } } } } catch (final HibernateException he) { throw new NoApplicableCodeException().causedBy(he) .withMessage("Exception thrown while requesting feature envelope for observation ids"); } return null; }
From source file:org.n52.sos.ds.hibernate.HibernateFeatureQueryHandler.java
License:Open Source License
@Override public SosEnvelope getEnvelopeForFeatureIDs(FeatureQueryHandlerQueryObject queryObject) throws OwsExceptionReport { final Session session = HibernateSessionHolder.getSession(queryObject.getConnection()); if (queryObject.isSetFeatureIdentifiers()) { try {/* ww w . j a va 2 s. co m*/ // XXX workaround for Hibernate Spatial's lack of support for // GeoDB's extent aggregate // see // http://www.hibernatespatial.org/pipermail/hibernatespatial-users/2013-August/000876.html Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect(); if (GeometryHandler.getInstance().isSpatialDatasource() && HibernateHelper.supportsFunction(dialect, HibernateConstants.FUNC_EXTENT)) { // Criteria featureExtentCriteria = // session.createCriteria(FeatureOfInterest.class) // .add(Restrictions.in(FeatureOfInterest.IDENTIFIER, // featureIDs)) // .setProjection(SpatialProjections.extent(FeatureOfInterest.GEOMETRY)); // LOGGER.debug("QUERY getEnvelopeForFeatureIDs(featureIDs): {}", // HibernateHelper.getSqlString(featureExtentCriteria)); // Geometry geom = (Geometry) // featureExtentCriteria.uniqueResult(); Geometry geom = (Geometry) session.createCriteria(FeatureOfInterest.class) .add(Restrictions.in(FeatureOfInterest.IDENTIFIER, queryObject.getFeatureIdentifiers())) .setProjection(SpatialProjections.extent(FeatureOfInterest.GEOMETRY)).uniqueResult(); if (geom != null) { int srid = geom.getSRID() > 0 ? geom.getSRID() : getStorageEPSG(); geom.setSRID(srid); geom = getGeometryHandler().switchCoordinateAxisFromToDatasourceIfNeeded(geom); return new SosEnvelope(geom.getEnvelopeInternal(), srid); } } else { final Envelope envelope = new Envelope(); final List<FeatureOfInterest> featuresOfInterest = new FeatureOfInterestDAO() .getFeatureOfInterestObject(queryObject.getFeatureIdentifiers(), session); for (final FeatureOfInterest feature : featuresOfInterest) { try { // TODO Check if prepareGeometryForResponse required // transform/switch // final Geometry geom = // getGeometryHandler().prepareGeometryForResponse(getGeomtery(feature), // queryObject.getRequestedSrid()); final Geometry geom = getGeomtery(feature, session); if (geom != null) { envelope.expandToInclude(geom.getEnvelopeInternal()); } } catch (final OwsExceptionReport owse) { LOGGER.warn(String.format("Error while adding '%s' to envelope!", feature.getFeatureOfInterestId()), owse); } } if (!envelope.isNull()) { return new SosEnvelope(envelope, getDefaultEPSG()); } } } catch (final HibernateException he) { throw new NoApplicableCodeException().causedBy(he) .withMessage("Exception thrown while requesting global feature envelope"); } } return null; }
From source file:org.n52.sos.ds.hibernate.testdata.TestDataConfiguratorInitializedListener.java
License:Open Source License
private boolean isAutoInsertGeoDB() throws OwsExceptionReport { HibernateSessionHolder sessionHolder = new HibernateSessionHolder(); Session session = sessionHolder.getSession(); Dialect dialect = ((SessionFactoryImplementor) session.getSessionFactory()).getDialect(); Properties props = ((SessionFactoryImplementor) session.getSessionFactory()).getProperties(); String url = null;/* w w w. j a v a 2 s . c om*/ Object urlObject = props.get(HIBERNATE_CONNECTION_URL); if (urlObject != null && urlObject instanceof String) { url = (String) urlObject; } sessionHolder.returnSession(session); return dialect != null & url != null && dialect instanceof GeoDBDialect && url.startsWith(AUTO_INSERT_H2_URL); }
From source file:org.n52.sos.ds.hibernate.util.HibernateHelper.java
License:Open Source License
/** * Get the SQL query string from HQL Query. * * @param query/*from ww w.j a v a 2 s . c o m*/ * HQL query to convert to SQL * @return SQL query string from HQL */ public static String getSqlString(Query query, Session session) { final QueryTranslatorFactory ast = new ASTQueryTranslatorFactory(); SessionFactory sessionFactory = session.getSessionFactory(); final QueryTranslatorImpl qt = (QueryTranslatorImpl) ast.createQueryTranslator("id", query.getQueryString(), Maps.newHashMap(), (SessionFactoryImplementor) sessionFactory, null); qt.compile(null, false); return qt.getSQLString(); }
From source file:org.n52.sos.ds.hibernate.util.HibernateHelper.java
License:Open Source License
public static Dialect getDialect(Session session) { return ((SessionFactoryImplementor) session.getSessionFactory()).getDialect(); }
From source file:org.n52.sos.ds.hibernate.util.HibernateMetadataCache.java
License:Open Source License
private Map<String, ClassMetadata> initClassMetadata(Session session) { return ImmutableMap.copyOf(session.getSessionFactory().getAllClassMetadata()); }