Example usage for org.hibernate Session setFlushMode

List of usage examples for org.hibernate Session setFlushMode

Introduction

In this page you can find the example usage for org.hibernate Session setFlushMode.

Prototype

@Deprecated
void setFlushMode(FlushMode flushMode);

Source Link

Document

Set the flush mode for this session.

Usage

From source file:ar.edu.utn.sigmaproject.webflow.Hibernate4FlowExecutionListener.java

License:Apache License

private Session createSession(RequestContext context) {
    final SessionBuilder sessionBuilder = sessionFactory.withOptions();
    if (entityInterceptor != null) {
        sessionBuilder.interceptor(entityInterceptor);
    }/* ww w . j  ava  2  s  . c  o m*/

    Session session = sessionBuilder.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    return session;
}

From source file:ariba.ui.meta.jpa.HibernateContext.java

License:Apache License

protected static EntityManager createEntityManager(EntityManagerFactory factory) {
    EntityManager em = factory.createEntityManager();
    Session session = (Session) em.getDelegate();
    session.setFlushMode(FlushMode.MANUAL);
    return em;/*from w w w  .  jav  a 2s.c  o  m*/
}

From source file:at.molindo.esi4j.module.hibernate.HibernateEntityResolver.java

License:Apache License

public void openResolveSession() {
    Session session = _localSession.get();

    if (session != null) {
        log.warn("session already open, now closing first");
        closeResolveSession();/*from  w ww  .  j a  v a 2s.com*/
        session = null;
    }

    session = getNewSession(getSessionFactory());
    session.setDefaultReadOnly(true);
    session.setCacheMode(CacheMode.GET);
    session.setFlushMode(FlushMode.MANUAL);
    session.beginTransaction();
    _localSession.set(session);
}

From source file:au.com.nicta.ct.db.CtManualFlush.java

License:Open Source License

public CtManualFlush(Session s) {
    this.s = s;
    fm = s.getFlushMode();
    s.setFlushMode(FlushMode.MANUAL);
}

From source file:com.adsapient.shared.service.AdSapientHibernateService.java

License:Open Source License

public static synchronized Session openSession() throws HibernateException {
    if (sessionFactory == null) {
        return null;
    }/*w  ww.  j  a va  2 s.  c o  m*/

    if (testSession != null) {
        return testSession;
    }

    Session session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.COMMIT);

    return session;
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@Override
public synchronized StorageTransaction newStorageTransaction() {
    assertPrepared();/*from  www  . ja v  a  2 s. c om*/
    Session session = factory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    return new HibernateStorageTransaction(this, session);
}

From source file:com.amalto.core.storage.hibernate.HibernateStorage.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override/*from   w  w w.  ja v  a  2  s.  c  o m*/
public void delete(Expression userQuery) {
    Session session = this.getCurrentSession();
    try {
        storageClassLoader.bind(Thread.currentThread());
        // Session session = factory.getCurrentSession();
        userQuery = userQuery.normalize(); // First do a normalize for correct optimization detection.
        // Check if optimized delete for one type (and no filter) is applicable
        if (userQuery instanceof Select) {
            Select select = (Select) userQuery;
            List<ComplexTypeMetadata> types = select.getTypes();
            if (types.size() == 1 && select.getCondition() == null) {
                FlushMode previousFlushMode = session.getFlushMode();
                try {
                    session.setFlushMode(FlushMode.ALWAYS); // Force Hibernate to actually send SQL query to
                                                            // database during delete.
                    ComplexTypeMetadata mainType = types.get(0);
                    TypeMapping mapping = mappingRepository.getMappingFromUser(mainType);
                    // Compute (and eventually sort) types to delete
                    List<ComplexTypeMetadata> typesToDelete;
                    MetadataRepository internalRepository = typeMappingRepository.getInternalRepository();
                    if (mapping instanceof ScatteredTypeMapping) {
                        MetadataVisitor<List<ComplexTypeMetadata>> transitiveClosure = new TypeTransitiveClosure();
                        List<ComplexTypeMetadata> typeClosure = mapping.getDatabase().accept(transitiveClosure);
                        typesToDelete = MetadataUtils.sortTypes(internalRepository, typeClosure);
                    } else {
                        Collection<ComplexTypeMetadata> subTypes = mapping.getDatabase().getSubTypes();
                        if (subTypes.isEmpty()) {
                            typesToDelete = Collections.singletonList(mapping.getDatabase());
                        } else {
                            typesToDelete = new ArrayList<ComplexTypeMetadata>(subTypes.size() + 1);
                            typesToDelete.add(mapping.getDatabase());
                            typesToDelete.addAll(subTypes);
                        }
                    }
                    Map<ComplexTypeMetadata, Map<String, List>> recordsToDeleteMap = new HashMap<ComplexTypeMetadata, Map<String, List>>();
                    for (ComplexTypeMetadata typeToDelete : typesToDelete) {
                        InboundReferences inboundReferences = new InboundReferences(typeToDelete);
                        Set<ReferenceFieldMetadata> references = internalRepository.accept(inboundReferences);
                        // Empty values from intermediate tables to this non instantiable type and unset inbound
                        // references
                        if (typeToDelete.equals(mainType)) {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.isMany()) {
                                    // No need to check for mandatory collections of references since constraint
                                    // cannot be expressed in db schema
                                    String formattedTableName = tableResolver.getCollectionTable(reference);
                                    session.createSQLQuery("delete from " + formattedTableName).executeUpdate(); //$NON-NLS-1$
                                } else {
                                    String referenceTableName = tableResolver
                                            .get(reference.getContainingType());
                                    if (referenceTableName.startsWith("X_ANONYMOUS")) { //$NON-NLS-1$
                                        session.createSQLQuery("delete from " + referenceTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    }
                                }
                            }
                        } else {
                            for (ReferenceFieldMetadata reference : references) {
                                if (reference.getContainingType().equals(mainType)) {
                                    HashMap<String, List> fieldsCondition = new HashMap<>();
                                    if (reference.isMany()) {
                                        // No need to check for mandatory collections of references since constraint
                                        // cannot
                                        // be expressed in db schema
                                        String formattedTableName = tableResolver.getCollectionTable(reference);
                                        session.createSQLQuery("delete from " + formattedTableName) //$NON-NLS-1$
                                                .executeUpdate();
                                    } else {
                                        String referenceTableName = tableResolver
                                                .get(reference.getContainingType());
                                        if (reference.getReferencedField() instanceof CompoundFieldMetadata) {
                                            FieldMetadata[] fields = ((CompoundFieldMetadata) reference
                                                    .getReferencedField()).getFields();
                                            for (FieldMetadata field : fields) {
                                                List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                        + tableResolver.get(field, reference.getName())
                                                        + " from " //$NON-NLS-1$
                                                        + referenceTableName).list();
                                                if (list == null || list.isEmpty()) {
                                                    continue;
                                                } else {
                                                    fieldsCondition.put(
                                                            tableResolver.get(reference.getReferencedField()),
                                                            list);
                                                }
                                            }
                                        } else {
                                            List list = session.createSQLQuery("select " //$NON-NLS-1$
                                                    + tableResolver.get(reference.getReferencedField(),
                                                            reference.getName())
                                                    + " from " + referenceTableName).list(); //$NON-NLS-1$
                                            if (list == null || list.isEmpty()) {
                                                continue;
                                            } else {
                                                fieldsCondition.put(
                                                        tableResolver.get(reference.getReferencedField()),
                                                        list);
                                            }
                                        }
                                        recordsToDeleteMap.put(typeToDelete, fieldsCondition);
                                    }
                                }
                            }
                        }
                    }
                    deleteData(mapping.getDatabase(), new HashMap<String, List>(), mapping);
                    for (Map.Entry<ComplexTypeMetadata, Map<String, List>> entry : recordsToDeleteMap
                            .entrySet()) {
                        // Empty values in type isMany=true reference
                        deleteData(entry.getKey(), entry.getValue(), mapping);
                    }
                } finally {
                    session.setFlushMode(previousFlushMode);
                }
                return;
            }
        }
        // Generic fall back for deletions (filter)
        if (userQuery instanceof Select) {
            ((Select) userQuery).setForUpdate(true);
        }
        Iterable<DataRecord> records = internalFetch(session, userQuery,
                Collections.<ResultsCallback>emptySet());
        for (DataRecord currentDataRecord : records) {
            ComplexTypeMetadata currentType = currentDataRecord.getType();
            List<ComplexTypeMetadata> types = new ArrayList<>();
            if (userQuery instanceof Select) {
                types.addAll(((Select) userQuery).getTypes());
            }
            if (types.isEmpty() || types.contains(currentType)) {
                TypeMapping mapping = mappingRepository.getMappingFromUser(currentType);
                if (mapping == null) {
                    throw new IllegalArgumentException(
                            "Type '" + currentType.getName() + "' does not have a database mapping."); //$NON-NLS-1$ //$NON-NLS-2$
                }
                Class<?> clazz = storageClassLoader.getClassFromType(mapping.getDatabase());

                Serializable idValue;
                Collection<FieldMetadata> keyFields = currentType.getKeyFields();
                if (keyFields.size() == 1) {
                    idValue = (Serializable) currentDataRecord.get(keyFields.iterator().next());
                } else {
                    List<Object> compositeIdValues = new LinkedList<Object>();
                    for (FieldMetadata keyField : keyFields) {
                        compositeIdValues.add(currentDataRecord.get(keyField));
                    }
                    idValue = ObjectDataRecordConverter.createCompositeId(storageClassLoader, clazz,
                            compositeIdValues);
                }

                Wrapper object = (Wrapper) session.get(clazz, idValue, LockOptions.READ);
                if (object != null) {
                    session.delete(object);
                } else {
                    LOGGER.warn("Instance of type '" + currentType.getName() + "' and ID '" + idValue.toString() //$NON-NLS-1$ //$NON-NLS-2$
                            + "' has already been deleted within same transaction."); //$NON-NLS-1$
                }
            }
        }
    } catch (ConstraintViolationException e) {
        throw new com.amalto.core.storage.exception.ConstraintViolationException(e);
    } catch (HibernateException e) {
        throw new RuntimeException(e);
    } finally {
        this.releaseSession();
        storageClassLoader.unbind(Thread.currentThread());
    }
}

From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcher.java

License:Apache License

/**
 * Configures the session.//from  w  w  w  .  j a v a2 s . co m
 * @param session
 *            the session
 */
private void configureSession(Session session) {
    session.setDefaultReadOnly(unitOfWork.readOnly());
    session.setCacheMode(unitOfWork.cacheMode());
    session.setFlushMode(unitOfWork.flushMode());
}

From source file:com.booleanworks.kryptopterus.application.MainHibernateUtil.java

License:Apache License

public Session getNewSession() {
    System.out.println("com.booleanworks.kryptopterus.application.MainHibernateUtil.getNewSession()");

    Session session;
    session = this.sessionFactory.openSession();
    session.setFlushMode(FlushModeType.AUTO);

    System.out.println("return session; => " + session.hashCode());
    return session;
}

From source file:com.byteslounge.spring.tx.MyOwnTxManager.java

License:Apache License

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException(
                "Pre-bound JDBC Connection found! HibernateTransactionManager does not support "
                        + "running within DataSourceTransactionManager if told to manage the DataSource itself. "
                        + "It is recommended to use a single HibernateTransactionManager for all transactions "
                        + "on a single DataSource, no matter whether Hibernate or JDBC access.");
    }/*from   w ww.  j a  va 2s. c om*/

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Session newSession = getSessionFactory().openSession();
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction");
            }
            txObject.setSession(newSession);
        }

        session = txObject.getSessionHolder().getSession();

        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            if (logger.isDebugEnabled()) {
                logger.debug("Preparing JDBC Connection of Hibernate Session [" + session + "]");
            }
            Connection con = ((SessionImplementor) session).connection();
            if (con.isClosed()) {
                System.out.println("Connection closed by exception");
            }
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
        } else {
            // Not allowed to change the transaction settings of the JDBC Connection.
            if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
                // We should set a specific isolation level but are not allowed to...
                throw new InvalidIsolationLevelException(
                        "HibernateTransactionManager is not allowed to support custom isolation levels: "
                                + "make sure that its 'prepareConnection' flag is on (the default) and that the "
                                + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default).");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session [" + session + "]");
            }
        }

        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushMode.MANUAL);
        }

        if (!definition.isReadOnly() && !txObject.isNewSession()) {
            // We need AUTO or COMMIT for a non-read-only transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(session.getFlushMode())) {
                session.setFlushMode(FlushMode.AUTO);
                txObject.getSessionHolder().setPreviousFlushMode(flushMode);
            }
        }

        Transaction hibTx;

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
            // Applies to all statements, also to inserts, updates and deletes!
            hibTx = session.getTransaction();
            hibTx.setTimeout(timeout);
            hibTx.begin();
        } else {
            // Open a plain Hibernate transaction without specified timeout.
            hibTx = session.beginTransaction();
        }

        // Add the Hibernate transaction to the session holder.
        txObject.getSessionHolder().setTransaction(hibTx);

        // Register the Hibernate Session's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            Connection con = ((SessionImplementor) session).connection();
            ConnectionHolder conHolder = new ConnectionHolder(con);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                conHolder.setTimeoutInSeconds(timeout);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
            }
            TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
            txObject.setConnectionHolder(conHolder);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    }

    catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                SessionFactoryUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}