List of usage examples for org.hibernate Session setFlushMode
@Deprecated
void setFlushMode(FlushMode flushMode);
From source file:org.beangle.commons.orm.hibernate.HibernateTransactionManager.java
License:Open Source 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 w w. j a v a 2 s. com*/ 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 [" + SessionUtils.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 [" + SessionUtils.toString(session) + "]"); } @SuppressWarnings("deprecation") 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' (BeangleTransactionFactory's default). " + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } if (logger.isDebugEnabled()) { logger.debug("Not preparing JDBC Connection of Hibernate Session [" + SessionUtils.toString(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.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) { @SuppressWarnings("deprecation") 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 (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 { SessionUtils.closeSession(session); } } throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } }
From source file:org.beangle.commons.orm.hibernate.HibernateTransactionManager.java
License:Open Source License
@Override protected void prepareForCommit(DefaultTransactionStatus status) { if (this.earlyFlushBeforeCommit && status.isNewTransaction()) { HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction(); Session session = txObject.getSessionHolder().getSession(); if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) { logger.debug("Performing an early flush for Hibernate transaction"); try { session.flush();/* www . j a va2 s . co m*/ } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } finally { session.setFlushMode(FlushMode.MANUAL); } } } }
From source file:org.beangle.commons.orm.hibernate.HibernateTransactionManager.java
License:Open Source License
@Override protected void doCleanupAfterCompletion(Object transaction) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; // Remove the session holder from the thread. if (txObject.isNewSessionHolder()) { TransactionSynchronizationManager.unbindResource(getSessionFactory()); }/*from www . j a v a 2 s. c om*/ // Remove the JDBC connection holder from the thread, if exposed. if (getDataSource() != null) { TransactionSynchronizationManager.unbindResource(getDataSource()); } Session session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && session.isConnected() && isSameConnectionForEntireSession(session)) { // We're running with connection release mode "on_close": We're able to reset // the isolation level and/or read-only flag of the JDBC Connection here. // Else, we need to rely on the connection pool to perform proper cleanup. try { @SuppressWarnings("deprecation") Connection con = session.connection(); DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (HibernateException ex) { logger.debug("Could not access JDBC Connection of Hibernate Session", ex); } } if (txObject.isNewSession()) { if (logger.isDebugEnabled()) { logger.debug( "Closing Hibernate Session [" + SessionUtils.toString(session) + "] after transaction"); } SessionUtils.closeSession(session); } else { if (logger.isDebugEnabled()) { logger.debug("Not closing pre-bound Hibernate Session [" + SessionUtils.toString(session) + "] after transaction"); } if (txObject.getSessionHolder().getPreviousFlushMode() != null) { session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode()); } if (!this.hibernateManagedSession) { session.disconnect(); } } txObject.getSessionHolder().clear(); }
From source file:org.beangle.orm.hibernate.BeangleSessionContext.java
License:Open Source License
/** * Retrieve the Spring-managed Session for the current thread, if any. *//*from www . jav a2s .c o m*/ public Session currentSession() throws HibernateException { SessionHolder sessionHolder = SessionUtils.currentSession(this.sessionFactory); Session session = sessionHolder.getSession(); // TODO what time enter into the code? if (TransactionSynchronizationManager.isSynchronizationActive() && !sessionHolder.isSynchronizedWithTransaction()) { TransactionSynchronizationManager .registerSynchronization(new SessionSynchronization(sessionHolder, this.sessionFactory)); 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.isManualFlushMode(flushMode) && !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { session.setFlushMode(FlushMode.AUTO); sessionHolder.setPreviousFlushMode(flushMode); } } return session; }
From source file:org.beangle.orm.hibernate.BeangleSessionContext.java
License:Open Source License
public void beforeCompletion() { Session session = this.sessionHolder.getSession(); if (this.sessionHolder.getPreviousFlushMode() != null) { // In case of pre-bound Session, restore previous flush mode. session.setFlushMode(this.sessionHolder.getPreviousFlushMode()); }//from ww w . j a v a 2s. c o m // Eagerly disconnect the Session here, to make release mode "on_close" work nicely. session.disconnect(); }
From source file:org.beangle.orm.hibernate.HibernateTransactionManager.java
License:Open Source 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 ww w . j ava2 s . c o m*/ Session session = null; try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { Session newSession = getSessionFactory().openSession(); txObject.setSession(newSession); } session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && isSameConnectionForEntireSession(session)) { // We're allowed to change the transaction settings of the JDBC Connection. Connection con = ((SessionImplementor) 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' (BeangleTransactionFactory's default). " + "Make sure that your SessionFactoryBean actually uses BeangleTransactionFactory: Your " + "Hibernate properties should *not* include a 'hibernate.transaction.factory_class' property!"); } } 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 { SessionUtils.closeSession(session); } } throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex); } }
From source file:org.beangle.orm.hibernate.HibernateTransactionManager.java
License:Open Source License
@Override protected void doCleanupAfterCompletion(Object transaction) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; // Remove the session holder from the thread. if (txObject.isNewSessionHolder()) { TransactionSynchronizationManager.unbindResource(getSessionFactory()); }/*from ww w. j av a2s. c o m*/ // Remove the JDBC connection holder from the thread, if exposed. if (getDataSource() != null) { TransactionSynchronizationManager.unbindResource(getDataSource()); } Session session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && session.isConnected() && isSameConnectionForEntireSession(session)) { // We're running with connection release mode "on_close": We're able to reset // the isolation level and/or read-only flag of the JDBC Connection here. // Else, we need to rely on the connection pool to perform proper cleanup. try { Connection con = ((SessionImplementor) session).connection(); DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (HibernateException ex) { logger.debug("Could not access JDBC Connection of Hibernate Session", ex); } } if (txObject.isNewSession()) { SessionUtils.closeSession(session); } else { if (txObject.getSessionHolder().getPreviousFlushMode() != null) { session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode()); } if (!this.hibernateManagedSession) session.disconnect(); } txObject.getSessionHolder().clear(); }
From source file:org.beangle.orm.hibernate.internal.SessionUtils.java
License:Open Source License
public static SessionHolder openSession(SessionFactory factory) throws DataAccessResourceFailureException, IllegalStateException { try {/* w w w . j a v a2 s .c o m*/ SessionHolder holder = (SessionHolder) getResource(factory); Session session = null; if (null == holder) { session = factory.openSession(); session.setFlushMode(FlushMode.MANUAL); holder = new SessionHolder(session); if (isEnableBinding(factory)) bindResource(factory, holder); } return holder; } catch (HibernateException ex) { throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex); } }
From source file:org.broadleafcommerce.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 { final 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;//from w w w . ja v a2 s.co m } if (FieldProviderResponse.HANDLED_BREAK == response) { break; } } if (!handled) { defaultFieldPersistenceProvider.filterProperties(new AddFilterPropertiesRequest(entity), unfilteredProperties); } //Order media field, map field and rule builder fields last, as they will have some validation components that depend on previous values Property[] sortedProperties = entity.getProperties(); Arrays.sort(sortedProperties, new Comparator<Property>() { @Override public int compare(Property o1, Property o2) { BasicFieldMetadata mo1 = (BasicFieldMetadata) mergedProperties.get(o1.getName()); BasicFieldMetadata mo2 = (BasicFieldMetadata) mergedProperties.get(o2.getName()); boolean isLate1 = mo1 != null && mo1.getFieldType() != null && mo1.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo1.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo1.getFieldType() || SupportedFieldType.MEDIA == mo1.getFieldType() || o1.getName().contains(FieldManager.MAPFIELDSEPARATOR)); boolean isLate2 = mo2 != null && mo2.getFieldType() != null && mo2.getName() != null && (SupportedFieldType.RULE_SIMPLE == mo2.getFieldType() || SupportedFieldType.RULE_WITH_QUANTITY == mo2.getFieldType() || SupportedFieldType.MEDIA == mo2.getFieldType() || o2.getName().contains(FieldManager.MAPFIELDSEPARATOR)); if (isLate1 && !isLate2) { return 1; } else if (!isLate1 && isLate2) { return -1; } return 0; } }); Session session = getPersistenceManager().getDynamicEntityDao().getStandardEntityManager() .unwrap(Session.class); FlushMode originalFlushMode = session.getFlushMode(); try { session.setFlushMode(FlushMode.MANUAL); RuntimeException entityPersistenceException = null; for (Property property : sortedProperties) { 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 = getBasicBroadleafType(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) { try { boolean isBreakDetected = false; for (FieldPersistenceProvider fieldPersistenceProvider : fieldPersistenceProviders) { if (!isBreakDetected || fieldPersistenceProvider.alwaysRun()) { FieldProviderResponse response = fieldPersistenceProvider .populateValue(request, instance); if (FieldProviderResponse.NOT_HANDLED != response) { handled = true; } if (FieldProviderResponse.HANDLED_BREAK == response) { isBreakDetected = true; } } } if (!handled) { defaultFieldPersistenceProvider.populateValue( new PopulateValueRequest(setId, fieldManager, property, metadata, returnType, value, persistenceManager, this), instance); } } catch (ParentEntityPersistenceException | javax.validation.ValidationException e) { entityPersistenceException = e; cleanupFailedPersistenceAttempt(instance); break; } } } 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 if (entityPersistenceException != null) { throw ExceptionHelper.refineException(entityPersistenceException.getCause()); } 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.castafiore.persistence.DaoImpl.java
License:Open Source License
public Session getReadOnlySession() { try {/* w w w.j ava 2s.co m*/ Session session = SESSION_THREAD.get(); if (session == null || !session.isOpen()) { session = getHibernateTemplate().getSessionFactory().openSession(); session.setFlushMode(FlushMode.MANUAL); //session.setCacheMode(CacheMode.IGNORE); SESSION_THREAD.set(session); } return session; } catch (Exception e) { //return HibernateUtil.getSession(getHibernateTemplate().getSessionFactory()); throw new RuntimeException(e); } }