List of usage examples for org.hibernate Session getFlushMode
@Override FlushModeType getFlushMode();
From source file:org.jboss.dashboard.workspace.WorkspacesManager.java
License:Apache License
public Workspace getWorkspaceByUrl(final String url) throws Exception { final Workspace[] workspace = new Workspace[1]; new HibernateTxFragment() { protected void txFragment(Session session) throws Exception { FlushMode oldFlushMode = session.getFlushMode(); session.setFlushMode(FlushMode.NEVER); Query q = session/*from www . j a v a 2 s . co m*/ .createQuery(" from " + WorkspaceImpl.class.getName() + " p where p.friendlyUrl = :url"); q.setString("url", url); q.setCacheable(true); List l = q.list(); if (l.size() == 1) { workspace[0] = (Workspace) l.get(0); } session.setFlushMode(oldFlushMode); } }.execute(); return workspace[0]; }
From source file:org.jspresso.framework.application.backend.persistence.hibernate.HibernateBackendController.java
License:Open Source License
private void initializeProperty(IComponent componentOrEntity, String propertyName) { Session hibernateSession = getHibernateSession(); FlushMode oldFlushMode = hibernateSession.getFlushMode(); try {/*from ww w . ja v a2 s. c om*/ // Temporary switch to a read-only session. hibernateSession.setFlushMode(FlushMode.MANUAL); try { currentInitializationSession = hibernateSession; performPropertyInitializationUsingSession(componentOrEntity, propertyName, hibernateSession); } finally { currentInitializationSession = null; } } finally { hibernateSession.setFlushMode(oldFlushMode); } }
From source file:org.kuali.rice.krad.dao.impl.BusinessObjectDaoJpa.java
License:Educational Community License
/** * @see org.kuali.rice.krad.dao.BusinessObjectDao#manageReadOnly(org.kuali.rice.krad.bo.PersistableBusinessObject) *///from ww w . j av a 2 s. c o m public PersistableBusinessObject manageReadOnly(PersistableBusinessObject bo) { Session session = ((HibernateEntityManager) entityManager).getSession(); FlushMode currentFlushMode = session.getFlushMode(); session.setFlushMode(FlushMode.MANUAL); // make sure the merge doesn't flush what we're trying to make read only PersistableBusinessObject managedBO = entityManager.merge(bo); session.setReadOnly(managedBO, true); session.setFlushMode(currentFlushMode); return managedBO; }
From source file:org.openmrs.api.db.hibernate.HibernateTransactionManagerFlushOnCommit.java
License:Open Source License
/** * @see org.springframework.orm.hibernate3.HibernateTransactionManager#doBegin(java.lang.Object, * org.springframework.transaction.TransactionDefinition) *//*from w ww. j a va2 s.c o m*/ @Override protected void doBegin(Object transaction, TransactionDefinition definition) { super.doBegin(transaction, definition); Session session = getSessionFactory().getCurrentSession(); if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.COMMIT); } }
From source file:org.seasar.hibernate3.impl.S2SessionFactoryImpl.java
License:Apache License
private void flushSession(Transaction tx) { Session session = (Session) txSessions_.get(tx); if (session == null || !session.isOpen() || session.getFlushMode().equals(FlushMode.NEVER)) { return;//from ww w . jav a2 s. c o m } session.flush(); }
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;// ww w . j av a 2 s. c om } 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.//from w w w . jav a 2 s.c om * @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; }
From source file:org.springframework.orm.hibernate3.HibernateTemplate.java
License:Apache License
/** * Check whether write operations are allowed on the given Session. * <p>Default implementation throws an InvalidDataAccessApiUsageException in * case of {@code FlushMode.MANUAL}. Can be overridden in subclasses. * @param session current Hibernate Session * @throws InvalidDataAccessApiUsageException if write operations are not allowed * @see #setCheckWriteOperations/*from ww w . j a va 2s .co m*/ * @see #getFlushMode() * @see #FLUSH_EAGER * @see org.hibernate.Session#getFlushMode() * @see org.hibernate.FlushMode#MANUAL */ protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException { if (isCheckWriteOperations() && getFlushMode() != FLUSH_EAGER && session.getFlushMode().lessThan(FlushMode.COMMIT)) { throw new InvalidDataAccessApiUsageException( "Write operations are not allowed in read-only mode (FlushMode.MANUAL): " + "Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition."); } }
From source file:org.springframework.orm.hibernate3.HibernateTransactionManager.java
License:Apache License
@Override @SuppressWarnings("deprecation") 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 . ja v a 2 s . co m*/ Session session = null; try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { Interceptor entityInterceptor = getEntityInterceptor(); Session newSession = (entityInterceptor != null ? getSessionFactory().openSession(entityInterceptor) : getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + SessionFactoryUtils.toString(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 [" + SessionFactoryUtils.toString(session) + "]"); } Connection con = session.connection(); 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). " + "Make sure that your LocalSessionFactoryBean actually uses SpringTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } if (logger.isDebugEnabled()) { logger.debug("Not preparing JDBC Connection of Hibernate Session [" + SessionFactoryUtils.toString(session) + "]"); } } if (definition.isReadOnly() && txObject.isNewSession()) { // Just set to MANUAL 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.lessThan(FlushMode.COMMIT)) { 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 = 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 (Throwable 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); txObject.setSessionHolder(null); } } throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } }
From source file:org.springframework.orm.hibernate3.SessionFactoryUtils.java
License:Apache License
/** * Get a Hibernate Session for the given SessionFactory. Is aware of and will * return any existing corresponding Session bound to the current thread, for * example when using {@link HibernateTransactionManager}. Will create a new * Session otherwise, if "allowCreate" is {@code true}. * <p>Same as {@link #getSession}, but throwing the original HibernateException. * @param sessionFactory Hibernate SessionFactory to create the session with * @param entityInterceptor Hibernate entity interceptor, or {@code null} if none * @param jdbcExceptionTranslator SQLExcepionTranslator to use for flushing the * Session on transaction synchronization (may be {@code null}) * @param allowCreate whether a non-transactional Session should be created * when no transactional Session can be found for the current thread * @return the Hibernate Session/*from ww w . j a va 2 s .c o m*/ * @throws HibernateException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and * "allowCreate" is {@code false} */ private static Session doGetSession(SessionFactory sessionFactory, Interceptor entityInterceptor, SQLExceptionTranslator jdbcExceptionTranslator, boolean allowCreate) throws HibernateException, IllegalStateException { Assert.notNull(sessionFactory, "No SessionFactory specified"); Object resource = TransactionSynchronizationManager.getResource(sessionFactory); if (resource instanceof Session) { return (Session) resource; } SessionHolder sessionHolder = (SessionHolder) resource; if (sessionHolder != null && !sessionHolder.isEmpty()) { // pre-bound Hibernate Session Session session = null; if (TransactionSynchronizationManager.isSynchronizationActive() && sessionHolder.doesNotHoldNonDefaultSession()) { // Spring transaction management is active -> // register pre-bound Session with it for transactional flushing. session = sessionHolder.getValidatedSession(); if (session != null && !sessionHolder.isSynchronizedWithTransaction()) { logger.debug("Registering Spring transaction synchronization for existing Hibernate Session"); TransactionSynchronizationManager.registerSynchronization(new SpringSessionSynchronization( sessionHolder, sessionFactory, jdbcExceptionTranslator, false)); sessionHolder.setSynchronizedWithTransaction(true); // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session // with FlushMode.MANUAL, which needs to allow flushing within the transaction. FlushMode flushMode = session.getFlushMode(); if (flushMode.lessThan(FlushMode.COMMIT) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } } else { // No Spring transaction management active -> try JTA transaction synchronization. session = getJtaSynchronizedSession(sessionHolder, sessionFactory, jdbcExceptionTranslator); } if (session != null) { return session; } } logger.debug("Opening Hibernate Session"); Session session = (entityInterceptor != null ? sessionFactory.openSession(entityInterceptor) : sessionFactory.openSession()); // Use same Session for further Hibernate actions within the transaction. // Thread object will get removed by synchronization at transaction completion. if (TransactionSynchronizationManager.isSynchronizationActive()) { // We're within a Spring-managed transaction, possibly from JtaTransactionManager. logger.debug("Registering Spring transaction synchronization for new Hibernate Session"); SessionHolder holderToUse = sessionHolder; if (holderToUse == null) { holderToUse = new SessionHolder(session); } else { holderToUse.addSession(session); } if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.MANUAL); } TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(holderToUse, sessionFactory, jdbcExceptionTranslator, true)); holderToUse.setSynchronizedWithTransaction(true); if (holderToUse != sessionHolder) { TransactionSynchronizationManager.bindResource(sessionFactory, holderToUse); } } else { // No Spring transaction management active -> try JTA transaction synchronization. registerJtaSynchronization(session, sessionFactory, jdbcExceptionTranslator, sessionHolder); } // Check whether we are allowed to return the Session. if (!allowCreate && !isSessionTransactional(session, sessionFactory)) { closeSession(session); throw new IllegalStateException("No Hibernate Session bound to thread, " + "and configuration does not allow creation of non-transactional one here"); } return session; }