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:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

boolean isKnownInDB(URI location, String queueName) {
    boolean known = false;

    Session session = null;
    Transaction transaction = null;/*from  w  w w  .  ja  v  a 2s .  c om*/
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session
                .createQuery(
                        String.format("SELECT count(location) FROM %s as cmd WHERE location = ?", queueName))
                .setParameter(0, location);
        Long result = (Long) query.setReadOnly(true).uniqueResult();
        known = (result != null && result.longValue() > 0);

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while testing if location '%s' is known.",
                e.getClass().getName(), location.toASCIIString()), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return known;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;
    Transaction transaction = null;/*from w  w w  .  j ava2 s.c  om*/
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

/**
 * First queries the DB to remove all known locations from the list and then updates
 * it with the new list./*from  w w  w. ja v  a  2  s .co m*/
 * 
 * @param profileID the ID of the {@link ICommandProfile}, newly created 
 * commands should belong to
 * @param depth depth of the new {@link ICommand} 
 * @param locations the locations to add to the DB
 * @return the number of known locations in the given list
 */
int storeUnknownLocations(int profileID, int depth, LinkedList<URI> locations) {
    if (locations == null || locations.size() == 0)
        return 0;

    int known = 0;
    Session session = null;
    Transaction transaction = null;
    try {
        // open session and transaction
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        // check the cache for URL existance and put the ones not known to the
        // cache into another list and remove them from the list which is checked
        // against the DB below
        known += storeUnknownInDoubleCache(profileID, depth, locations, session);

        // check which URLs are already known against the DB
        if (locations.size() > 0)
            known += storeUnknownInDB(profileID, depth, locations, session, 10);

        transaction.commit();

        // signal writer that a new URL is available
        this.writerThread.signalNewDbData();

        return known;
    } catch (Throwable e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error(String.format("Unexpected '%s' while writing %d new commands to db.",
                e.getClass().getName(), Integer.valueOf(locations.size())), e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return 0;
}

From source file:org.projectforge.database.XmlDump.java

License:Open Source License

/**
 * @param reader//from  ww  w.  ja  va 2  s .  co  m
 * @return Only for test cases.
 */
public XStreamSavingConverter restoreDatabase(final Reader reader) {
    final XStreamSavingConverter xstreamSavingConverter = new XStreamSavingConverter() {

        @Override
        protected Serializable getOriginalIdentifierValue(final Object obj) {
            return HibernateUtils.getIdentifier(obj);
        }

        @Override
        public Serializable onBeforeSave(final Session session, final Object obj) {
            log.info("Object " + obj);
            if (obj instanceof PFUserDO) {
                final PFUserDO user = (PFUserDO) obj;
                return save(user, user.getRights());
            } else if (obj instanceof AbstractRechnungDO<?>) {
                final AbstractRechnungDO<? extends AbstractRechnungsPositionDO> rechnung = (AbstractRechnungDO<?>) obj;
                final List<? extends AbstractRechnungsPositionDO> positions = rechnung.getPositionen();
                rechnung.setPositionen(null); // Need to nullable positions first (otherwise insert fails).
                final Serializable id = save(rechnung);
                if (positions != null) {
                    for (final AbstractRechnungsPositionDO pos : positions) {
                        if (pos.getKostZuweisungen() != null) {
                            final List<KostZuweisungDO> zuweisungen = pos.getKostZuweisungen();
                            pos.setKostZuweisungen(null); // Need to nullable first (otherwise insert fails).
                            save(pos);
                            if (pos instanceof RechnungsPositionDO) {
                                ((RechnungDO) rechnung).addPosition((RechnungsPositionDO) pos);
                            } else {
                                ((EingangsrechnungDO) rechnung).addPosition((EingangsrechnungsPositionDO) pos);
                            }
                            if (zuweisungen != null) {
                                for (final KostZuweisungDO zuweisung : zuweisungen) {
                                    pos.addKostZuweisung(zuweisung);
                                    save(zuweisung);
                                }
                            }
                        }
                    }
                }
                return id;
            } else if (obj instanceof AuftragDO) {
                final AuftragDO auftrag = (AuftragDO) obj;
                return save(auftrag, auftrag.getPositionen());
            }
            return super.onBeforeSave(session, obj);
        }
    };
    // UserRightDO is inserted on cascade while inserting PFUserDO.
    xstreamSavingConverter.appendIgnoredObjects(embeddedClasses);
    xstreamSavingConverter.appendOrderedType(PFUserDO.class, GroupDO.class, TaskDO.class, KundeDO.class,
            ProjektDO.class, Kost1DO.class, Kost2ArtDO.class, Kost2DO.class, AuftragDO.class, //
            RechnungDO.class, EingangsrechnungDO.class, EmployeeSalaryDO.class, KostZuweisungDO.class, //
            UserPrefEntryDO.class, UserPrefDO.class, //
            AccessEntryDO.class, GroupTaskAccessDO.class, ConfigurationDO.class);
    Session session = null;
    try {
        final SessionFactory sessionFactory = hibernate.getSessionFactory();
        session = sessionFactory.openSession(EmptyInterceptor.INSTANCE);
        session.setFlushMode(FlushMode.AUTO);
        final XStream xstream = new XStream(new DomDriver());
        xstream.setMode(XStream.ID_REFERENCES);
        xstreamSavingConverter.setSession(session);
        xstream.registerConverter(xstreamSavingConverter, 10);
        xstream.registerConverter(new UserRightIdSingleValueConverter(), 20);
        xstream.registerConverter(new UserPrefAreaSingleValueConverter(), 19);
        // alle Objekte Laden und speichern
        xstream.fromXML(reader);

        xstreamSavingConverter.saveObjects();
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(reader);
        if (session != null) {
            session.close();
        }
    }
    return xstreamSavingConverter;
}

From source file:org.projectforge.framework.persistence.database.XmlDump.java

License:Open Source License

/**
 * @param reader//  w ww.  j a v  a 2s .  co m
 * @return Only for test cases.
 */
public XStreamSavingConverter restoreDatabase(final Reader reader) {
    final List<AbstractPlugin> plugins = pluginAdminService.getActivePlugin();
    final XStreamSavingConverter xstreamSavingConverter = new XStreamSavingConverter() {

        @Override
        protected Serializable getOriginalIdentifierValue(final Object obj) {
            return HibernateUtils.getIdentifier(obj);
        }

        @Override
        public Serializable onBeforeSave(final Session session, final Object obj) {
            log.info("Object " + obj);
            if (obj instanceof PFUserDO) {
                final PFUserDO user = (PFUserDO) obj;
                return save(user, user.getRights());
            } else if (obj instanceof AbstractRechnungDO<?>) {

                final AbstractRechnungDO<? extends AbstractRechnungsPositionDO> rechnung = (AbstractRechnungDO<?>) obj;
                final List<? extends AbstractRechnungsPositionDO> positions = rechnung.getPositionen();
                final KontoDO konto = rechnung.getKonto();
                if (konto != null) {
                    save(konto);
                    rechnung.setKonto(null);
                }
                rechnung.setPositionen(null); // Need to nullable positions first (otherwise insert fails).
                final Serializable id = save(rechnung);
                if (konto != null) {
                    rechnung.setKonto(konto);
                }
                if (positions != null) {
                    for (final AbstractRechnungsPositionDO pos : positions) {
                        if (pos.getKostZuweisungen() != null) {
                            final List<KostZuweisungDO> zuweisungen = pos.getKostZuweisungen();
                            pos.setKostZuweisungen(null); // Need to nullable first (otherwise insert fails).
                            save(pos);
                            if (pos instanceof RechnungsPositionDO) {
                                ((RechnungDO) rechnung).addPosition((RechnungsPositionDO) pos);
                            } else {
                                ((EingangsrechnungDO) rechnung).addPosition((EingangsrechnungsPositionDO) pos);
                            }
                            if (zuweisungen != null) {
                                for (final KostZuweisungDO zuweisung : zuweisungen) {
                                    pos.addKostZuweisung(zuweisung);
                                    save(zuweisung);
                                }
                            }
                        }
                    }
                }
                return id;
            } else if (obj instanceof AuftragDO) {
                final AuftragDO auftrag = (AuftragDO) obj;
                return save(auftrag, auftrag.getPositionen());
            }
            if (plugins != null) {
                for (final AbstractPlugin plugin : plugins) {
                    try {
                        plugin.onBeforeRestore(this, obj);
                    } catch (final Exception ex) {
                        log.error("Error in Plugin while restoring object: " + ex.getMessage(), ex);
                    }
                }
            }
            for (final XmlDumpHook xmlDumpHook : xmlDumpHooks) {
                try {
                    xmlDumpHook.onBeforeRestore(userXmlPreferencesDao, this, obj);
                } catch (final Exception ex) {
                    log.error("Error in XmlDumpHook while restoring object: " + ex.getMessage(), ex);
                }
            }
            return super.onBeforeSave(session, obj);
        }

        /**
         * @see org.projectforge.framework.persistence.xstream.XStreamSavingConverter#onAfterSave(java.lang.Object,
         *      java.io.Serializable)
         */
        @Override
        public void onAfterSave(final Object obj, final Serializable id) {
            if (plugins != null) {
                for (final AbstractPlugin plugin : plugins) {
                    plugin.onAfterRestore(this, obj, id);
                }
            }
        }
    };
    // UserRightDO is inserted on cascade while inserting PFUserDO.
    xstreamSavingConverter.appendIgnoredObjects(embeddedClasses);
    // automatically detect insert order.
    List<EntityMetadata> ents = emf.getMetadataRepository().getTableEntities();
    List<Class<?>> classList = ents.stream().map((e) -> e.getJavaType()).collect(Collectors.toList());
    // first entities with now deps
    Collections.reverse(classList);

    xstreamSavingConverter.appendOrderedType(PFUserDO.class, GroupDO.class, TaskDO.class, KundeDO.class,
            ProjektDO.class, Kost1DO.class, Kost2ArtDO.class, Kost2DO.class, AuftragDO.class, //
            RechnungDO.class, EingangsrechnungDO.class, EmployeeSalaryDO.class, KostZuweisungDO.class, //
            UserPrefEntryDO.class, UserPrefDO.class, //
            AccessEntryDO.class, GroupTaskAccessDO.class, ConfigurationDO.class);
    xstreamSavingConverter.appendOrderedType(classList.toArray(new Class<?>[] {}));

    //    if (plugins != null) {
    //      for (final AbstractPlugin plugin : plugins) {
    //        xstreamSavingConverter.appendOrderedType(plugin.getPersistentEntities());
    //      }
    //    }
    Session session = null;
    try {
        final SessionFactory sessionFactory = hibernate.getSessionFactory();
        session = HibernateCompatUtils.openSession(sessionFactory, EmptyInterceptor.INSTANCE);
        session.setFlushMode(FlushMode.AUTO);
        final XStream xstream = XStreamHelper.createXStream();
        xstream.setMode(XStream.ID_REFERENCES);
        xstreamSavingConverter.setSession(session);
        xstream.registerConverter(xstreamSavingConverter, 10);
        xstream.registerConverter(new UserRightIdSingleValueConverter(userRights), 20);
        xstream.registerConverter(new UserPrefAreaSingleValueConverter(), 19);
        // alle Objekte Laden und speichern
        xstream.fromXML(reader);

        xstreamSavingConverter.saveObjects();
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(reader);
        if (session != null) {
            session.close();
        }
    }
    return xstreamSavingConverter;
}

From source file:org.riotfamily.common.hibernate.ThreadBoundHibernateTemplate.java

License:Apache License

@Override
protected Object doExecute(HibernateCallback action, boolean enforceNewSession, boolean enforceNativeSession)
        throws DataAccessException {

    Assert.notNull(action, "Callback object must not be null");

    Session oldSession = null;//  ww  w .  ja  v a 2s  . co  m
    Session session = (enforceNewSession
            ? SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor())
            : getSession());

    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager
            .getResource(getSessionFactory());

    boolean existingTransaction = !enforceNewSession
            && (!isAllowCreate() || (sessionHolder != null && sessionHolder.containsSession(session)));

    if (existingTransaction) {
        log.debug("Found thread-bound Session for LongConversationTemplate");
    } else {
        if (sessionHolder != null) {
            oldSession = sessionHolder.getSession();
            sessionHolder.addSession(session);
        } else {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
        }
    }

    FlushMode previousFlushMode = null;
    try {
        previousFlushMode = applyFlushMode(session, existingTransaction);
        enableFilters(session);
        Session sessionToExpose = (enforceNativeSession || isExposeNativeSession() ? session
                : createSessionProxy(session));
        Object result = action.doInHibernate(sessionToExpose);
        flushIfNecessary(session, existingTransaction);
        return result;
    } catch (HibernateException ex) {
        throw convertHibernateAccessException(ex);
    } catch (SQLException ex) {
        throw convertJdbcAccessException(ex);
    } catch (RuntimeException ex) {
        // Callback code threw application exception...
        throw ex;
    } finally {
        if (existingTransaction) {
            log.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
            disableFilters(session);
            if (previousFlushMode != null) {
                session.setFlushMode(previousFlushMode);
            }
        } else {
            SessionFactoryUtils.closeSession(session);
            if (oldSession != null) {
                sessionHolder.addSession(oldSession);
            } else {
                TransactionSynchronizationManager.unbindResource(getSessionFactory());
            }
        }
    }
}

From source file:org.sakaiproject.scorm.ui.player.HibernateFilter.java

License:Educational Community License

@Override
protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
    Session session = SessionFactoryUtils.getSession(sessionFactory, true);
    //set the FlushMode to auto in order to save objects.
    session.setFlushMode(FlushMode.AUTO);
    return session;
}

From source file:org.seasar.hibernate3.interceptor.ReadOnlySessionInterceptor.java

License:Apache License

public Object invoke(MethodInvocation invocation) throws Throwable {
    Session session = sessionFactory.getSession();
    session.setFlushMode(FlushMode.NEVER);

    return invocation.proceed();
}

From source file:org.sparkcommerce.openadmin.server.service.persistence.module.BasicPersistenceModule.java

License:Apache License

@Override
public Serializable createPopulatedInstance(Serializable instance, Entity entity,
        Map<String, FieldMetadata> unfilteredProperties, Boolean setId, Boolean validateUnsubmittedProperties)
        throws ValidationException {
    Map<String, FieldMetadata> mergedProperties = filterOutCollectionMetadata(unfilteredProperties);
    FieldManager fieldManager = getFieldManager();
    boolean handled = false;
    for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
        FieldProviderResponse response = fieldPersistenceProvider
                .filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties);
        if (FieldProviderResponse.NOT_HANDLED != response) {
            handled = true;//w  w  w .j a va 2s.  co m
        }
        if (FieldProviderResponse.HANDLED_BREAK == response) {
            break;
        }
    }
    if (!handled) {
        defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity),
                unfilteredProperties);
    }
    Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager()
            .unwrap(Session.class);
    FlushMode originalFlushMode = session.getFlushMode();
    try {
        session.setFlushMode(FlushMode.MANUAL);
        for (Property property : entity.getProperties()) {
            BasicFieldMetadata metadata = (BasicFieldMetadata) mergedProperties.get(property.getName());
            Class<?> returnType;
            if (!property.getName().contains(FieldManager.MAPFIELDSEPARATOR)
                    && !property.getName().startsWith("__")) {
                Field field = fieldManager.getField(instance.getClass(), property.getName());
                if (field == null) {
                    LOG.debug("Unable to find a bean property for the reported property: " + property.getName()
                            + ". Ignoring property.");
                    continue;
                }
                returnType = field.getType();
            } else {
                if (metadata == null) {
                    LOG.debug("Unable to find a metadata property for the reported property: "
                            + property.getName() + ". Ignoring property.");
                    continue;
                }
                returnType = getMapFieldType(instance, fieldManager, property);
                if (returnType == null) {
                    returnType = getBasicSparkType(metadata.getFieldType());
                }
            }
            if (returnType == null) {
                throw new IllegalAccessException(
                        "Unable to determine the value type for the property (" + property.getName() + ")");
            }
            String value = property.getValue();
            if (metadata != null) {
                Boolean mutable = metadata.getMutable();
                Boolean readOnly = metadata.getReadOnly();

                if (metadata.getFieldType().equals(SupportedFieldType.BOOLEAN)) {
                    if (value == null) {
                        value = "false";
                    }
                }

                if ((mutable == null || mutable) && (readOnly == null || !readOnly)) {
                    if (value != null) {
                        handled = false;
                        PopulateValueRequest request = new PopulateValueRequest(setId, fieldManager, property,
                                metadata, returnType, value, persistenceManager, this);

                        boolean attemptToPopulate = true;
                        for (PopulateValueRequestValidator validator : populateValidators) {
                            PropertyValidationResult validationResult = validator.validate(request, instance);
                            if (!validationResult.isValid()) {
                                entity.addValidationError(property.getName(),
                                        validationResult.getErrorMessage());
                                attemptToPopulate = false;
                            }
                        }

                        if (attemptToPopulate) {
                            for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) {
                                FieldProviderResponse response = fieldPersistenceProvider.populateValue(request,
                                        instance);
                                if (FieldProviderResponse.NOT_HANDLED != response) {
                                    handled = true;
                                }
                                if (FieldProviderResponse.HANDLED_BREAK == response) {
                                    break;
                                }
                            }
                            if (!handled) {
                                defaultFieldPersistenceProvider
                                        .populateValue(
                                                new PopulateValueRequest(setId, fieldManager, property,
                                                        metadata, returnType, value, persistenceManager, this),
                                                instance);
                            }
                        }
                    } else {
                        try {
                            if (fieldManager.getFieldValue(instance, property.getName()) != null
                                    && (metadata.getFieldType() != SupportedFieldType.ID || setId)
                                    && metadata.getFieldType() != SupportedFieldType.PASSWORD) {
                                if (fieldManager.getFieldValue(instance, property.getName()) != null) {
                                    property.setIsDirty(true);
                                }
                                fieldManager.setFieldValue(instance, property.getName(), null);
                            }
                        } catch (FieldNotAvailableException e) {
                            throw new IllegalArgumentException(e);
                        }
                    }
                }
            }
        }
        validate(entity, instance, mergedProperties, validateUnsubmittedProperties);
        //if validation failed, refresh the current instance so that none of the changes will be persisted
        if (entity.isValidationFailure()) {
            //only refresh the instance if it was managed to begin with
            if (persistenceManager.getDynamicEntityDao().getStandardEntityManager().contains(instance)) {
                persistenceManager.getDynamicEntityDao().refresh(instance);
            }

            //re-initialize the valid properties for the entity in order to deal with the potential of not
            //completely sending over all checkbox/radio fields
            List<Serializable> entityList = new ArrayList<Serializable>(1);
            entityList.add(instance);
            Entity invalid = getRecords(mergedProperties, entityList, null, null)[0];
            invalid.setPropertyValidationErrors(entity.getPropertyValidationErrors());
            invalid.overridePropertyValues(entity);

            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, List<String>> entry : invalid.getPropertyValidationErrors().entrySet()) {
                Iterator<String> itr = entry.getValue().iterator();
                while (itr.hasNext()) {
                    sb.append(entry.getKey());
                    sb.append(" : ");
                    sb.append(itr.next());
                    if (itr.hasNext()) {
                        sb.append(" / ");
                    }
                }
            }

            throw new ValidationException(invalid, "The entity has failed validation - " + sb.toString());
        } else {
            fieldManager.persistMiddleEntities();
        }
    } catch (IllegalAccessException e) {
        throw new PersistenceException(e);
    } catch (InstantiationException e) {
        throw new PersistenceException(e);
    } finally {
        session.setFlushMode(originalFlushMode);
    }
    return instance;
}

From source file:org.springframework.orm.hibernate3.HibernateAccessor.java

License:Apache License

/**
 * Apply the flush mode that's been specified for this accessor
 * to the given Session./* ww  w.j a v  a 2s  . c o m*/
 * @param session the current Hibernate Session
 * @param existingTransaction if executing within an existing transaction
 * @return the previous flush mode to restore after the operation,
 * or {@code null} if none
 * @see #setFlushMode
 * @see org.hibernate.Session#setFlushMode
 */
protected FlushMode applyFlushMode(Session session, boolean existingTransaction) {
    if (getFlushMode() == FLUSH_NEVER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.lessThan(FlushMode.COMMIT)) {
                session.setFlushMode(FlushMode.MANUAL);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.MANUAL);
        }
    } else if (getFlushMode() == FLUSH_EAGER) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.AUTO)) {
                session.setFlushMode(FlushMode.AUTO);
                return previousFlushMode;
            }
        } else {
            // rely on default FlushMode.AUTO
        }
    } else if (getFlushMode() == FLUSH_COMMIT) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.COMMIT);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.COMMIT);
        }
    } else if (getFlushMode() == FLUSH_ALWAYS) {
        if (existingTransaction) {
            FlushMode previousFlushMode = session.getFlushMode();
            if (!previousFlushMode.equals(FlushMode.ALWAYS)) {
                session.setFlushMode(FlushMode.ALWAYS);
                return previousFlushMode;
            }
        } else {
            session.setFlushMode(FlushMode.ALWAYS);
        }
    }
    return null;
}