List of usage examples for org.hibernate FlushMode AUTO
FlushMode AUTO
To view the source code for org.hibernate FlushMode AUTO.
Click Source Link
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."); }// ww w . j av a 2 s . co 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.broadleafcommerce.common.dao.GenericEntityDaoImpl.java
License:Apache License
@Override public void enableAutoFlushMode() { em.unwrap(Session.class).setFlushMode(FlushMode.AUTO); }
From source file:org.codehaus.grepo.query.hibernate.repository.DefaultHibernateRepository.java
License:Apache License
/** * Apply the flush mode that's been specified. * * @param sessionHolder The current session holder. * @param queryOptions the query options. *//*from w ww. j av a 2 s.com*/ protected void applyFlushMode(CurrentSessionHolder sessionHolder, HibernateQueryOptions queryOptions) { HibernateFlushMode flushModeToUse = getFlushMode(queryOptions); if (flushModeToUse != null) { FlushMode flushModeToSet = null; FlushMode previousFlushMode = null; if (flushModeToUse == HibernateFlushMode.MANUAL) { if (sessionHolder.isExistingTransaction()) { previousFlushMode = sessionHolder.getSession().getFlushMode(); if (!previousFlushMode.lessThan(FlushMode.COMMIT)) { flushModeToSet = FlushMode.MANUAL; } } else { flushModeToSet = FlushMode.MANUAL; } } else if (flushModeToUse == HibernateFlushMode.EAGER) { if (sessionHolder.isExistingTransaction()) { previousFlushMode = sessionHolder.getSession().getFlushMode(); if (!previousFlushMode.equals(FlushMode.AUTO)) { flushModeToSet = FlushMode.AUTO; } } // else rely on default FlushMode.AUTO } else if (flushModeToUse == HibernateFlushMode.COMMIT) { if (sessionHolder.isExistingTransaction()) { previousFlushMode = sessionHolder.getSession().getFlushMode(); if (previousFlushMode.equals(FlushMode.AUTO) || previousFlushMode.equals(FlushMode.ALWAYS)) { flushModeToSet = FlushMode.COMMIT; } } else { flushModeToSet = FlushMode.COMMIT; } } else if (flushModeToUse == HibernateFlushMode.ALWAYS) { if (sessionHolder.isExistingTransaction()) { previousFlushMode = sessionHolder.getSession().getFlushMode(); if (!previousFlushMode.equals(FlushMode.ALWAYS)) { flushModeToSet = FlushMode.ALWAYS; } } else { flushModeToSet = FlushMode.ALWAYS; } } if (flushModeToSet != null) { logger.debug("Setting flushMode to '{}' for generic repository execution", flushModeToSet); sessionHolder.getSession().setFlushMode(flushModeToSet); } if (previousFlushMode != null) { sessionHolder.setPreviousFlushMode(previousFlushMode); } } }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java
License:Apache License
/** * Sets the target object to read-write, allowing Hibernate to dirty check it and auto-flush changes. * * @see #setObjectToReadyOnly(Object, org.hibernate.SessionFactory) * * @param target The target object/* ww w . j a va 2 s. c om*/ * @param sessionFactory The SessionFactory instance */ public static void setObjectToReadWrite(final Object target, SessionFactory sessionFactory) { HibernateTemplate template = new HibernateTemplate(sessionFactory); template.setExposeNativeSession(true); template.execute(new HibernateCallback<Void>() { public Void doInHibernate(Session session) throws HibernateException, SQLException { if (canModifyReadWriteState(session, target)) { SessionImplementor sessionImpl = (SessionImplementor) session; EntityEntry ee = sessionImpl.getPersistenceContext().getEntry(target); if (ee != null && ee.getStatus() == Status.READ_ONLY) { Object actualTarget = target; if (target instanceof HibernateProxy) { actualTarget = ((HibernateProxy) target).getHibernateLazyInitializer() .getImplementation(); } session.setReadOnly(actualTarget, false); session.setFlushMode(FlushMode.AUTO); incrementVersion(target); } } return null; } }); }
From source file:org.codehaus.groovy.grails.orm.hibernate.GrailsSessionContext.java
License:Apache License
/** * Retrieve the Spring-managed Session for the current thread, if any. */// w w w. j a v a 2s .c om public Session currentSession() throws HibernateException { Object value = TransactionSynchronizationManager.getResource(sessionFactory); if (value instanceof Session) { return (Session) value; } if (value instanceof SessionHolder) { SessionHolder sessionHolder = (SessionHolder) value; Session session = sessionHolder.getSession(); if (TransactionSynchronizationManager.isSynchronizationActive() && !sessionHolder.isSynchronizedWithTransaction()) { TransactionSynchronizationManager .registerSynchronization(createSpringSessionSynchronization(sessionHolder)); 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; } if (jtaSessionContext != null) { Session session = jtaSessionContext.currentSession(); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager .registerSynchronization(createSpringFlushSynchronization(session)); } return session; } if (allowCreate) { // be consistent with older HibernateTemplate behavior return createSession(value); } throw new HibernateException("No Session found for current thread"); }
From source file:org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor.java
License:Apache License
public void setReadWrite() { getSession().setFlushMode(FlushMode.AUTO); }
From source file:org.codehaus.groovy.grails.orm.hibernate.support.HibernatePersistenceContextInterceptor.java
License:Apache License
public void init() { if (incNestingCount() > 1) { return;/*from ww w .j a v a 2 s . c o m*/ } SessionFactory sf = getSessionFactory(); if (TransactionSynchronizationManager.hasResource(sf)) { // Do not modify the Session: just set the participate flag. setParticipate(true); } else { setParticipate(false); LOG.debug("Opening single Hibernate session in HibernatePersistenceContextInterceptor"); Session session = getSession(); GrailsHibernateUtil.enableDynamicFilterEnablerIfPresent(sf, session); session.setFlushMode(FlushMode.AUTO); TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); } }
From source file:org.codehaus.groovy.grails.orm.hibernate.validation.UniqueConstraint.java
License:Apache License
@Override protected void processValidate(final Object target, final Object propertyValue, Errors errors) { if (!unique) { return;/* www . ja v a2 s.c o m*/ } final Object id; try { id = InvokerHelper.invokeMethod(target, "ident", null); } catch (Exception e) { throw new GrailsRuntimeException("Target of [unique] constraints [" + target + "] is not a domain instance. Unique constraint can only be applied to to domain classes and not custom user types or embedded instances"); } HibernateTemplate hibernateTemplate = getHibernateTemplate(); if (hibernateTemplate == null) throw new IllegalStateException("Unable use [unique] constraint, no Hibernate SessionFactory found!"); List<?> results = hibernateTemplate.executeFind(new HibernateCallback<List<?>>() { public List<?> doInHibernate(Session session) throws HibernateException { session.setFlushMode(FlushMode.MANUAL); try { boolean shouldValidate = true; Class<?> constraintClass = constraintOwningClass; if (propertyValue != null && DomainClassArtefactHandler.isDomainClass(propertyValue.getClass())) { shouldValidate = session.contains(propertyValue); } if (shouldValidate) { GrailsApplication application = (GrailsApplication) applicationContext .getBean(GrailsApplication.APPLICATION_ID); GrailsDomainClass domainClass = (GrailsDomainClass) application .getArtefact(DomainClassArtefactHandler.TYPE, constraintClass.getName()); if (domainClass != null && !domainClass.isRoot()) { GrailsDomainClassProperty property = domainClass .getPropertyByName(constraintPropertyName); while (property.isInherited() && domainClass != null) { domainClass = (GrailsDomainClass) application.getArtefact( DomainClassArtefactHandler.TYPE, domainClass.getClazz().getSuperclass().getName()); if (domainClass != null) { property = domainClass.getPropertyByName(constraintPropertyName); } } constraintClass = domainClass != null ? domainClass.getClazz() : constraintClass; } Criteria criteria = session.createCriteria(constraintClass) .add(Restrictions.eq(constraintPropertyName, propertyValue)); if (uniquenessGroup != null) { for (Object anUniquenessGroup : uniquenessGroup) { String uniquenessGroupPropertyName = (String) anUniquenessGroup; Object uniquenessGroupPropertyValue = GrailsClassUtils .getPropertyOrStaticPropertyOrFieldValue(target, uniquenessGroupPropertyName); if (uniquenessGroupPropertyValue != null && DomainClassArtefactHandler .isDomainClass(uniquenessGroupPropertyValue.getClass())) { try { // We are merely verifying that the object is not transient here session.lock(uniquenessGroupPropertyValue, LockMode.NONE); } catch (TransientObjectException e) { shouldValidate = false; } } if (shouldValidate) { criteria.add(Restrictions.eq(uniquenessGroupPropertyName, uniquenessGroupPropertyValue)); } else { break; // we aren't validating, so no point continuing } } } if (shouldValidate) { return criteria.list(); } return Collections.EMPTY_LIST; } return Collections.EMPTY_LIST; } finally { session.setFlushMode(FlushMode.AUTO); } } }); if (results.isEmpty()) { return; } boolean reject = false; if (id != null) { Object existing = results.get(0); Object existingId = null; try { existingId = InvokerHelper.invokeMethod(existing, "ident", null); } catch (Exception e) { // result is not a domain class } if (!id.equals(existingId)) { reject = true; } } else { reject = true; } if (reject) { Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue }; rejectValue(target, errors, UNIQUE_CONSTRAINT, args, getDefaultMessage(DEFAULT_NOT_UNIQUE_MESSAGE_CODE)); } }
From source file:org.egov.egf.web.actions.report.DayBookReportAction.java
License:Open Source License
@Validations(requiredFields = { @RequiredFieldValidator(fieldName = "startDate", message = "", key = FinancialConstants.REQUIRED), @RequiredFieldValidator(fieldName = "endDate", message = "", key = FinancialConstants.REQUIRED), @RequiredFieldValidator(fieldName = "fundId", message = "", key = FinancialConstants.REQUIRED), }) @ValidationErrorPage(value = FinancialConstants.STRUTS_RESULT_PAGE_SEARCH) @ReadOnly/*from w w w. j a v a2 s.co m*/ @Action(value = "/report/dayBookReport-ajaxSearch") public String ajaxSearch() throws TaskFailedException { if (LOGGER.isDebugEnabled()) LOGGER.debug("dayBookAction | Search | start"); prepareResultList(); if (LOGGER.isDebugEnabled()) LOGGER.debug("dayBookAction | list | End"); heading = getGLHeading(); prepareNewForm(); persistenceService.getSession().setFlushMode(FlushMode.AUTO); return "result"; }
From source file:org.egov.egf.web.actions.report.OpeningBalanceReportAction.java
License:Open Source License
@ReadOnly @Validations(requiredFields = {// ww w.j a v a 2s . c o m @RequiredFieldValidator(fieldName = "finYear", message = "", key = FinancialConstants.REQUIRED) }) @ValidationErrorPage(value = FinancialConstants.STRUTS_RESULT_PAGE_SEARCH) @Action(value = "/report/openingBalanceReport-ajaxSearch") public String ajaxSearch() throws TaskFailedException { if (LOGGER.isDebugEnabled()) LOGGER.debug("OpeningBalanceReportAction | Search | start"); try { openingBalanceDisplayList = openingBalance.getOBReport(openingBalanceReport); } catch (final ValidationException e) { throw new ValidationException(e.getErrors()); } catch (final Exception e) { throw new ApplicationRuntimeException(e.getMessage()); } if (LOGGER.isDebugEnabled()) LOGGER.debug("OpeningBalanceReportAction | list | End"); heading = getGLHeading(); prepareNewForm(); persistenceService.getSession().setFlushMode(FlushMode.AUTO); return "result"; }