List of usage examples for org.hibernate StatelessSession getTransaction
Transaction getTransaction();
From source file:au.org.theark.lims.model.dao.BiospecimenDao.java
License:Open Source License
protected void setSubjectUidSequenceLock(Study study, boolean lock) { // Stateless sessions should be used to avoid locking the record for future update // by getSession(), which relies on the "open session filter" mechanism StatelessSession session = getStatelessSession(); Transaction tx = session.getTransaction(); tx.begin();// w ww . j a v a 2s. co m BiospecimenUidSequence biospecimenUidSeq = getBiospecimenUidSequence(study); if (biospecimenUidSeq == null) { // create a new record if it doens't exist biospecimenUidSeq = new BiospecimenUidSequence(); biospecimenUidSeq.setStudyNameId(study.getName()); biospecimenUidSeq.setUidSequence(new Integer(0)); biospecimenUidSeq.setInsertLock(lock); session.insert(biospecimenUidSeq); } else { biospecimenUidSeq.setInsertLock(lock); session.update(biospecimenUidSeq); } tx.commit(); session.close(); }
From source file:com.ephesoft.dcma.dbexport.DbExporter.java
License:Open Source License
private void exportMetaDataToDB(final String dbTable, final String batchId, final String batchClass, final String docType, final String docField, final String docFieldValue, final String mappedDbTableColumn) throws DCMAApplicationException { String errorMessage = "DB Export Plugin: Problem occured in updating database table "; Connection connection = null; try {/*from w w w. j a v a2 s . c om*/ LOGGER.info("Preparing Query.."); connection = dynamicHibernateDao.getConnectionProvider().getConnection(); StatelessSession statelessSession = dynamicHibernateDao.getStatelessSession(connection); Transaction transaction = statelessSession.getTransaction(); StringBuffer dbQueryBuffer = new StringBuffer(DbExportConstant.INSERT_INTO); dbQueryBuffer.append(dbTable); String columnNames = prepareColumnNamesString(mappedDbTableColumn); dbQueryBuffer.append(columnNames); String values = prepareQueryValues(batchId, batchClass, docType, docField, docFieldValue); dbQueryBuffer.append(values); String dbQuery = null; dbQuery = dbQueryBuffer.toString(); LOGGER.info("Prepared query : " + dbQuery); SQLQuery query = dynamicHibernateDao.createUpdateOrInsertQuery(statelessSession, dbQuery); transaction.begin(); int result = query.executeUpdate(); transaction.commit(); statelessSession.close(); LOGGER.info("DB Export Plugin: Result of SQL commital transaction = " + result); } catch (HibernateException e) { LOGGER.error(errorMessage + dbTable + e.getMessage(), e); throw new DCMAApplicationException(errorMessage + dbTable + e.getMessage(), e); } catch (SQLException e) { LOGGER.error(errorMessage + dbTable + e.getMessage(), e); throw new DCMAApplicationException(errorMessage + dbTable + e.getMessage(), e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { LOGGER.error("Error closing the database session: " + e.getMessage(), e); } } if (dynamicHibernateDao != null) { dynamicHibernateDao.closeSession(); } } }
From source file:com.trifork.stamdata.persistence.StatelessPersistenceFilter.java
License:Mozilla Public License
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { StatelessSession session = null; try {/*from ww w . jav a 2 s. c o m*/ session = sessionProvider.get(); session.beginTransaction(); Transaction transaction = session.beginTransaction(); transaction.setTimeout(5); chain.doFilter(request, response); session.getTransaction().commit(); } catch (Exception e) { try { session.getTransaction().rollback(); } catch (Exception ex) { } throw new ServletException(e); } }
From source file:edu.utah.further.core.data.hibernate.listeners.PreUpdatePreventNullOverwriteListener.java
License:Apache License
@SuppressWarnings("resource") @Override//from ww w . j a v a2s . c o m public boolean onPreUpdate(final PreUpdateEvent event) { if (log.isDebugEnabled()) { log.debug("Received pre-update event"); } final EntityPersister entityPersister = event.getPersister(); final EntityMode entityMode = entityPersister.guessEntityMode(event.getEntity()); final Connection connection = getConnection(entityPersister); final StatelessSession session = entityPersister.getFactory().openStatelessSession(connection); session.beginTransaction(); final Serializable entityId = entityPersister.getIdentifier(event.getEntity(), (SessionImplementor) session); final Object existingEntity = session.get(event.getEntity().getClass(), entityId); if (log.isDebugEnabled()) { log.debug("Loaded existing entity " + existingEntity); } boolean updatedExistingEntity = false; for (int i = 0; i < entityPersister.getPropertyNames().length; i++) { final Object oldPropValue = entityPersister.getPropertyValue(existingEntity, i, entityMode); if (oldPropValue == null) { if (log.isDebugEnabled()) { log.debug("Found a property in the existing " + "entity that was null, checking new entity"); } final Object newPropValue = entityPersister.getPropertyValue(event.getEntity(), i, entityMode); if (!(newPropValue instanceof Collection<?>) && newPropValue != null) { if (log.isDebugEnabled()) { log.debug("The new entity contains a non-null " + "value, updating existing entity"); } entityPersister.setPropertyValue(existingEntity, i, newPropValue, entityMode); updatedExistingEntity = true; } } } if (updatedExistingEntity) { entityPersister.getFactory().getCurrentSession().cancelQuery(); session.update(existingEntity); } session.getTransaction().commit(); session.close(); return updatedExistingEntity; }
From source file:org.geolatte.demo1.services.RiverService.java
License:Open Source License
@Path("/cities") @GET/* w w w . j a v a2 s .c o m*/ @Produces(MediaType.APPLICATION_JSON) public List<PlaceTo> getEndangeredCities(@QueryParam("x") final float x, @QueryParam("y") final float y) { StatelessSession session = HibernateUtil.getSessionFactory().openStatelessSession(); try { // Begin unit of work session.beginTransaction(); SimpleTransformerSink<PlaceTo> sink = new SimpleTransformerSink<PlaceTo>(); ClosedTransformerChain chain = TransformerChainFactory.<Geometry, PlaceTo>newChain() .add(new RiverSegmentSource(x, y, session)) // <Geometry> .add(new Buffer()) // <Geometry> -> <Geometry> .add(new GetCitiesWithinBounds(session)) // <Geometry> -> [<Place>] .addFilter(new FilterDuplicates<Place>()) // <Place> -> <Place> .add(new PlaceToTransferObject()) // <Place> -> <PlaceTo> .last(sink); // collect chain.addTransformerEventListener(new TransformerEventListener() { @Override public void ErrorOccurred(TransformerErrorEvent event) { // Log errors here } }); chain.run(); List<PlaceTo> endangeredPlaces = sink.getCollectedOutput(); session.getTransaction().commit(); return endangeredPlaces; } catch (Exception ex) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); } finally { session.close(); } return Collections.emptyList(); }
From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java
License:Open Source License
@Override public void delete(List<String> externalIds, String providerKey, boolean includeDescendants) throws RepositoryException { if (externalIds.isEmpty()) { return;// ww w . j a v a 2 s .c o m } StatelessSession session = null; try { List<Integer> hashes = new LinkedList<Integer>(); for (String externalId : externalIds) { int hash = externalId.hashCode(); hashes.add(hash); } session = hibernateSessionFactory.openStatelessSession(); session.beginTransaction(); // delete all session.createQuery( "delete from UuidMapping where providerKey=:providerKey and externalIdHash in (:externalIds)") .setString("providerKey", providerKey).setParameterList("externalIds", hashes).executeUpdate(); if (includeDescendants) { // delete descendants Query selectStmt = session .createQuery( "from UuidMapping where providerKey=:providerKey and externalId like :externalId") .setString("providerKey", providerKey); for (String externalId : externalIds) { selectStmt.setString("externalId", externalId + "/%"); List<?> descendants = selectStmt.list(); for (Object mapping : descendants) { UuidMapping m = (UuidMapping) mapping; session.delete(m); invalidateCache(m.getExternalIdHash(), providerKey); } } } session.getTransaction().commit(); for (String externalId : externalIds) { int hash = externalId.hashCode(); invalidateCache(hash, providerKey); } } catch (Exception e) { if (session != null) { session.getTransaction().rollback(); } throw new RepositoryException(e); } finally { if (session != null) { session.close(); } } }
From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java
License:Open Source License
@Override public String getExternalIdentifier(String internalId) throws RepositoryException { String externalId = null;//from www . ja v a 2 s . co m StatelessSession session = null; try { session = getHibernateSessionFactory().openStatelessSession(); session.beginTransaction(); UuidMapping mapping = (UuidMapping) session.get(UuidMapping.class, internalId); if (mapping != null) { externalId = mapping.getExternalId(); } session.getTransaction().commit(); } catch (Exception e) { if (session != null) { session.getTransaction().rollback(); } throw new RepositoryException(e); } finally { if (session != null) { session.close(); } } return externalId; }
From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java
License:Open Source License
@Override public String getInternalIdentifier(String externalId, String providerKey) throws RepositoryException { int hash = externalId.hashCode(); String cacheKey = getCacheKey(hash, providerKey); String uuid = getIdentifierCache().get(cacheKey) != null ? (String) getIdentifierCache().get(cacheKey).getObjectValue() : null;/* w w w. ja v a2s. com*/ if (uuid == null) { StatelessSession session = null; try { session = getHibernateSessionFactory().openStatelessSession(); session.beginTransaction(); List<?> list = session .createQuery("from UuidMapping where providerKey=:providerKey and externalIdHash=:idHash") .setString("providerKey", providerKey).setLong("idHash", hash).setReadOnly(true).list(); if (list.size() > 0) { uuid = ((UuidMapping) list.get(0)).getInternalUuid(); getIdentifierCache().put(new Element(cacheKey, uuid, true)); } session.getTransaction().commit(); } catch (Exception e) { if (session != null) { session.getTransaction().rollback(); } throw new RepositoryException(e); } finally { if (session != null) { session.close(); } } } return uuid; }
From source file:org.jahia.modules.external.id.ExternalProviderInitializerServiceImpl.java
License:Open Source License
@Override public void removeProvider(String providerKey) throws RepositoryException { SessionFactory hibernateSession = getHibernateSessionFactory(); StatelessSession session = null; try {/*w ww . ja v a 2 s. c o m*/ session = hibernateSession.openStatelessSession(); session.beginTransaction(); int deletedCount = session.createQuery("delete from ExternalProviderID where providerKey=:providerKey") .setString("providerKey", providerKey).executeUpdate(); if (deletedCount > 0) { logger.info("Deleted external provider entry for key {}", providerKey); deletedCount = session.createQuery("delete from UuidMapping where providerKey=:providerKey") .setString("providerKey", providerKey).executeUpdate(); logger.info("Deleted {} identifier mapping entries for external provider with key {}", deletedCount, providerKey); } else { logger.info("No external provider entry found for key {}", providerKey); } session.getTransaction().commit(); } catch (Exception e) { if (session != null) { session.getTransaction().rollback(); } throw new RepositoryException( "Issue when removing external provider entry and identifier mappings for provider key " + providerKey, e); } finally { if (session != null) { session.close(); } } }
From source file:org.jahia.modules.ugp.showcase.DbUserGroupProvider.java
License:Open Source License
@Override public JahiaGroup getGroup(String name) throws GroupNotFoundException { JahiaGroup foundGroup = null;//from w w w.java2 s . c o m StatelessSession hib = sessionFactoryBean.openStatelessSession(); hib.beginTransaction(); try { @SuppressWarnings("unchecked") List<Group> groups = hib.createCriteria(Group.class).add(Restrictions.idEq(name)).list(); foundGroup = !groups.isEmpty() ? toGroup(groups.iterator().next()) : null; hib.getTransaction().commit(); } catch (HibernateException e) { logger.error(e.getMessage(), e); hib.getTransaction().rollback(); } finally { hib.close(); } if (foundGroup == null) { throw new GroupNotFoundException("Unable to find group " + name + " for the provider " + getKey()); } return foundGroup; }