Example usage for org.hibernate StatelessSession beginTransaction

List of usage examples for org.hibernate StatelessSession beginTransaction

Introduction

In this page you can find the example usage for org.hibernate StatelessSession beginTransaction.

Prototype

Transaction beginTransaction();

Source Link

Document

Begin a unit of work and return the associated Transaction object.

Usage

From source file:org.openbravo.test.dal.DalPerformanceProxyTest.java

License:Open Source License

@Test
public void testStatelessBPCreate() {
    try {/*from w  ww  .  j a  va 2 s . co  m*/
        setTestAdminContext();

        final StatelessSession session = SessionFactoryController.getInstance().getSessionFactory()
                .openStatelessSession();
        session.beginTransaction();
        for (int i = 0; i < CNT; i++) {
            BusinessPartner bp = OBProvider.getInstance().get(BusinessPartner.class);

            // Generating random strings for testing
            UUID name = UUID.randomUUID();
            UUID key = UUID.randomUUID();

            bp.setName(name.toString());
            bp.setSearchKey(key.toString());

            bp.setBusinessPartnerCategory(createReferencedObject(Category.class, TEST_BP_CATEGORY_ID));

            // note the following things are currently done in the OBInterceptor
            // it is quite easy to add a util method which can do this in a generic
            // way for any business object
            bp.setOrganization(createReferencedObject(Organization.class, TEST_ORG_ID));
            bp.setClient(createReferencedObject(Client.class, TEST_CLIENT_ID));
            bp.setCreatedBy(createReferencedObject(User.class, "100"));
            bp.setCreationDate(new Date());
            bp.setUpdatedBy(createReferencedObject(User.class, "100"));
            bp.setUpdated(new Date());

            session.insert(BusinessPartner.ENTITY_NAME, bp);
            // session.refresh(BusinessPartner.ENTITY_NAME, bp);
            Assert.assertTrue(bp.getId() != null);
        }
        session.getTransaction().commit();
    } catch (Exception e) {
        throw new OBException(e);
    }
}

From source file:org.openspaces.persistency.hibernate.StatelessHibernateExternalDataSource.java

License:Open Source License

/**
 * Perform the given bulk changes using Hibernate {@link org.hibernate.StatelessSession}. First,
 * tries to perform "optimistic" operations without checking in advance for existence of certain
 * entity. If this fails, will try and perform the same operations again, simply with checking
 * if the entry exists or not./*from w w w  . j av a  2  s .co m*/
 */
public void executeBulk(List<BulkItem> bulkItems) throws DataSourceException {
    StatelessSession session = getSessionFactory().openStatelessSession();
    Transaction tr = session.beginTransaction();
    Exception batchModeException = null;
    try {
        for (BulkItem bulkItem : bulkItems) {
            if (!isManaged(bulkItem))
                continue;

            switch (bulkItem.getOperation()) {
            case BulkItem.REMOVE:
                executeRemove(session, bulkItem);
                break;
            case BulkItem.WRITE:
                executeWrite(session, bulkItem);
                break;
            case BulkItem.UPDATE:
                executeUpdate(session, bulkItem);
                break;
            case BulkItem.PARTIAL_UPDATE:
                executePartialUpdate(session, bulkItem);
                break;
            default:
                break;
            }
        }
        tr.commit();
    } catch (Exception e) {
        rollbackTx(tr);
        batchModeException = new DataSourceException("Failed to execute bulk operation in batch mode", e);
    } finally {
        closeSession(session);
    }
    if (batchModeException == null) {
        // all is well, return
        return;
    } else {
        batchingLogger.error("Ignoring Hibernate StaleStateException, trying with exists batching");
    }

    // if something went wrong, do it with exists checks

    Object latest = null;
    session = getSessionFactory().openStatelessSession();
    tr = session.beginTransaction();
    try {
        for (BulkItem bulkItem : bulkItems) {
            if (!isManaged(bulkItem))
                continue;

            latest = bulkItem;
            switch (bulkItem.getOperation()) {
            case BulkItem.REMOVE:
                executeRemoveIfExists(session, bulkItem);
                break;
            case BulkItem.WRITE:
                executeWriteIfExists(session, bulkItem);
                break;
            case BulkItem.UPDATE:
                executeUpdateIfExists(session, bulkItem);
                break;
            case BulkItem.PARTIAL_UPDATE:
                executePartialUpdateIfExists(session, bulkItem);
            default:
                break;
            }
        }
        tr.commit();
    } catch (Exception e) {
        rollbackTx(tr);
        throw new DataSourceException("Failed to execute bulk operation, latest object [" + latest + "]", e);
    } finally {
        closeSession(session);
    }
}

From source file:org.openspaces.persistency.hibernate.StatelessHibernateSpaceSynchronizationEndpoint.java

License:Open Source License

private void executeDataSyncOperations(DataSyncOperation[] dataSyncOperations) {
    StatelessSession session = getSessionFactory().openStatelessSession();
    Transaction tr = session.beginTransaction();
    Exception batchModeException = null;
    try {//from w  w w.  jav a 2  s .co  m
        for (DataSyncOperation dataSyncOperation : dataSyncOperations) {
            if (!isManaged(dataSyncOperation))
                continue;

            switch (dataSyncOperation.getDataSyncOperationType()) {
            case REMOVE:
                executeRemove(session, dataSyncOperation);
                break;
            case WRITE:
                executeWrite(session, dataSyncOperation);
                break;
            case UPDATE:
                executeUpdate(session, dataSyncOperation);
                break;
            case PARTIAL_UPDATE:
                executePartialUpdate(session, dataSyncOperation);
                break;
            default:
                break;
            }
        }
        tr.commit();
    } catch (Exception e) {
        rollbackTx(tr);
        batchModeException = new DataSourceException("Failed to execute bulk operation in batch mode", e);
    } finally {
        closeSession(session);
    }
    if (batchModeException == null) {
        // all is well, return
        return;
    } else {
        batchingLogger.error("Ignoring Hibernate StaleStateException, trying with exists batching");
    }

    // if something went wrong, do it with exists checks

    Object latest = null;
    session = getSessionFactory().openStatelessSession();
    tr = session.beginTransaction();
    try {
        for (DataSyncOperation dataSyncOperation : dataSyncOperations) {
            if (!isManaged(dataSyncOperation))
                continue;

            latest = dataSyncOperation;
            switch (dataSyncOperation.getDataSyncOperationType()) {
            case REMOVE:
                executeRemoveIfExists(session, dataSyncOperation);
                break;
            case WRITE:
                executeWriteIfExists(session, dataSyncOperation);
                break;
            case UPDATE:
                executeUpdateIfExists(session, dataSyncOperation);
                break;
            case PARTIAL_UPDATE:
                executePartialUpdateIfExists(session, dataSyncOperation);
            default:
                break;
            }
        }
        tr.commit();
    } catch (Exception e) {
        rollbackTx(tr);
        throw new SpaceSynchronizationEndpointException(
                "Failed to execute bulk operation, latest object [" + latest + "]", e);
    } finally {
        closeSession(session);
    }
}

From source file:org.squashtest.tm.service.internal.api.repository.HibernateSqlQueryRunner.java

License:Open Source License

private <T> T executeQuery(String selectQuery, QueryExecution<Query> execution) {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
    StatelessSession s = sessionFactory.openStatelessSession();
    Transaction tx = s.beginTransaction();

    T res = null;/*from www  .ja v a  2 s.co m*/

    try {
        SQLQuery q = s.createSQLQuery(selectQuery);
        res = execution.<T>executeQuery(q);
        tx.commit();
    } catch (HibernateException e) {
        tx.rollback();
        throw e;
    } finally {
        s.close();

    }

    return res;
}

From source file:org.squashtest.tm.service.internal.campaign.coercers.extenders.CampaignLibraryExtender.java

License:Open Source License

@Override
public Collection<? extends Serializable> doCoerce(Collection<? extends Serializable> ids) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {/*from w  w w . ja  v  a2 s .com*/
        Query q = s.createQuery(
                "select distinct l.id from CampaignLibrary l join l.rootContent c where c.id in (:clnIds)");
        q.setParameterList("clnIds", ids);
        return q.list();

    } finally {
        tx.commit();
        s.close();
    }
}

From source file:org.squashtest.tm.service.internal.campaign.coercers.extenders.CampaignLibraryNodePathEdgeExtender.java

License:Open Source License

@Override
public Collection<? extends Serializable> doCoerce(Collection<? extends Serializable> coercedIds) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {//from   ww w  .j a v  a 2s .com
        Query q = s.createQuery(
                "select distinct edge.ancestorId from CampaignPathEdge edge where edge.descendantId in (:clnIds) and depth=1");
        q.setParameterList("clnIds", coercedIds);
        coercedIds.addAll(q.list());
        return coercedIds;

    } finally {
        tx.commit();
        s.close();
    }
}

From source file:org.squashtest.tm.service.internal.campaign.coercers.extenders.TestSuiteToIterationExtender.java

License:Open Source License

@Override
public Collection<? extends Serializable> doCoerce(Collection<? extends Serializable> ids) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {/*  w  w  w.jav  a2s.  c om*/
        Query q = s.createQuery(
                "select distinct i.id from Iteration i join i.testSuites ts where ts.id in (:tsids)");
        q.setParameterList("tsids", ids);
        return q.list();

    } finally {
        tx.commit();
        s.close();
    }
}

From source file:org.squashtest.tm.service.internal.campaign.coercers.IterationToCampaignIdsCoercer.java

License:Open Source License

@Override
public Collection<? extends Serializable> coerce(Object ids) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {/*from  w w  w  . j a v a2s. c  o  m*/
        Query q = s.createQuery(
                "select distinct c.id from Iteration i join i.campaign c where i.id in (:iterIds)");
        q.setParameterList("iterIds", (Collection<? extends Serializable>) ids);
        return q.list();

    } finally {
        tx.commit();
        s.close();
    }
}

From source file:org.squashtest.tm.service.internal.campaign.coercers.TestSuiteToIterationCoercerForUniqueId.java

License:Open Source License

@Override
public Serializable coerce(Object id) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {//w  w  w  . j  a v  a  2  s  .  c om
        Query q = s.createSQLQuery(
                "SELECT DISTINCT iteration_id FROM iteration_test_suite WHERE test_suite_id = :suiteId");
        q.setParameter("suiteId", id);
        return (Serializable) q.uniqueResult();

    } finally {
        tx.commit();
        s.close();
    }
}

From source file:org.squashtest.tm.service.internal.requirement.coercers.extenders.RequirementLibraryExtender.java

License:Open Source License

@Override
public Collection<? extends Serializable> doCoerce(Collection<? extends Serializable> ids) {
    StatelessSession s = hibernateStatelessSessionHelper.openStatelessSession();
    Transaction tx = s.beginTransaction();

    try {//from w  ww  .jav a  2 s. c  o m
        Query q = s.createQuery(
                "select distinct l.id from RequirementLibrary l join l.rootContent c where c.id in (:rlnIds) ");
        q.setParameterList("rlnIds", ids);
        return q.list();

    } finally {
        tx.commit();
        s.close();
    }
}