List of usage examples for org.hibernate Session setFlushMode
@Deprecated
void setFlushMode(FlushMode flushMode);
From source file:org.springframework.orm.hibernate43.SpringSessionContext.java
License:Apache License
/** * Retrieve the Spring-managed Session for the current thread, if any. *///from www . j a v a 2 s . com public Session currentSession() throws HibernateException { Object value = TransactionSynchronizationManager.getResource(this.sessionFactory); if (value instanceof Session) { return (Session) value; } else if (value instanceof SessionHolder) { SessionHolder sessionHolder = (SessionHolder) value; Session session = sessionHolder.getSession(); if (TransactionSynchronizationManager.isSynchronizationActive() && !sessionHolder.isSynchronizedWithTransaction()) { TransactionSynchronizationManager.registerSynchronization( new SpringSessionSynchronization(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; } else if (this.jtaSessionContext != null) { Session session = this.jtaSessionContext.currentSession(); if (TransactionSynchronizationManager.isSynchronizationActive()) { TransactionSynchronizationManager.registerSynchronization(new SpringFlushSynchronization(session)); } return session; } else { throw new HibernateException("No Session found for current thread"); } }
From source file:org.springframework.orm.hibernate5.HibernateTransactionManager.java
License:Apache License
@Override protected void doBegin(Object transaction, TransactionDefinition definition) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) { throw new IllegalTransactionStateException( "Pre-bound JDBC Connection found! HibernateTransactionManager does not support " + "running within DataSourceTransactionManager if told to manage the DataSource itself. " + "It is recommended to use a single HibernateTransactionManager for all transactions " + "on a single DataSource, no matter whether Hibernate or JDBC access."); }/*from w w w .ja v a2 s . c o m*/ Session session = null; try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { Interceptor entityInterceptor = getEntityInterceptor(); Session newSession = (entityInterceptor != null ? getSessionFactory().withOptions().interceptor(entityInterceptor).openSession() : getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction"); } txObject.setSession(newSession); } session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && isSameConnectionForEntireSession(session)) { // We're allowed to change the transaction settings of the JDBC Connection. if (logger.isDebugEnabled()) { logger.debug("Preparing JDBC Connection of Hibernate Session [" + session + "]"); } Connection con = ((SessionImplementor) session).connection(); Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition); txObject.setPreviousIsolationLevel(previousIsolationLevel); if (this.allowResultAccessAfterCompletion && !txObject.isNewSession()) { int currentHoldability = con.getHoldability(); if (currentHoldability != ResultSet.HOLD_CURSORS_OVER_COMMIT) { txObject.setPreviousHoldability(currentHoldability); con.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); } } } 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' (the default for JDBC)."); } if (logger.isDebugEnabled()) { logger.debug("Not preparing JDBC Connection of Hibernate Session [" + 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 (session.getFlushMode().equals(FlushMode.MANUAL)) { 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 (Throwable ex) { if (txObject.isNewSession()) { try { if (session.getTransaction().getStatus() == TransactionStatus.ACTIVE) { 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.hibernate5.HibernateTransactionManager.java
License:Apache License
@Override protected void doCleanupAfterCompletion(Object transaction) { HibernateTransactionObject txObject = (HibernateTransactionObject) transaction; // Remove the session holder from the thread. if (txObject.isNewSessionHolder()) { TransactionSynchronizationManager.unbindResource(getSessionFactory()); }//ww w .j a v a 2 s. com // Remove the JDBC connection holder from the thread, if exposed. if (getDataSource() != null) { TransactionSynchronizationManager.unbindResource(getDataSource()); } Session session = txObject.getSessionHolder().getSession(); if (this.prepareConnection && isPhysicallyConnected(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(); Integer previousHoldability = txObject.getPreviousHoldability(); if (previousHoldability != null) { con.setHoldability(previousHoldability); } DataSourceUtils.resetConnectionAfterTransaction(con, txObject.getPreviousIsolationLevel()); } catch (HibernateException ex) { logger.debug("Could not access JDBC Connection of Hibernate Session", ex); } catch (Throwable ex) { logger.debug("Could not reset JDBC Connection after transaction", ex); } } if (txObject.isNewSession()) { if (logger.isDebugEnabled()) { logger.debug("Closing Hibernate Session [" + session + "] after transaction"); } SessionFactoryUtils.closeSession(session); } else { if (logger.isDebugEnabled()) { logger.debug("Not closing pre-bound Hibernate Session [" + session + "] after transaction"); } if (txObject.getSessionHolder().getPreviousFlushMode() != null) { session.setFlushMode(txObject.getSessionHolder().getPreviousFlushMode()); } if (!this.allowResultAccessAfterCompletion && !this.hibernateManagedSession) { disconnectOnCompletion(session); } } txObject.getSessionHolder().clear(); }
From source file:org.springframework.orm.hibernate5.SpringSessionSynchronization.java
License:Apache License
@Override public void beforeCompletion() { try {//from ww w. j a va2 s .c o m 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()); } // Eagerly disconnect the Session here, to make release mode "on_close" work nicely. session.disconnect(); } finally { // Unbind at this point if it's a new Session... if (this.newSession) { TransactionSynchronizationManager.unbindResource(this.sessionFactory); this.holderActive = false; } } }
From source file:org.springframework.orm.jpa.vendor.HibernateJpaDialect.java
License:Apache License
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException { FlushMode flushMode = session.getFlushMode(); if (readOnly) { // We should suppress flushing for a read-only transaction. if (!flushMode.equals(FlushMode.MANUAL)) { session.setFlushMode(FlushMode.MANUAL); return flushMode; }//w w w .ja v a 2 s . co m } else { // We need AUTO or COMMIT for a non-read-only transaction. if (flushMode.lessThan(FlushMode.COMMIT)) { session.setFlushMode(FlushMode.AUTO); return flushMode; } } // No FlushMode change needed... return null; }
From source file:org.squale.squalecommon.enterpriselayer.facade.rule.AuditComputing.java
License:Open Source License
/** * Calcul des pratiques//from w w w . j a v a 2 s.c o m * Chaque pratique est calcule, son rsultat est crit en base de donnes * @param pSession session * @param pProject projet * @param pAudit audit * @param pPractices pratiques * @throws JrafDaoException si erreur */ private static void computePracticesResults(ISession pSession, ProjectBO pProject, AuditBO pAudit, Map pPractices) throws JrafDaoException { // Les pratiques sont tries par par type // de composant pour eviter les appels multiples de recuperation des // composants du projet Map kindPractices = splitPracticesByKind(pPractices); // On traite sparement les pratiques de niveau projet computeProjectPractices(pSession, pProject, pAudit, (Collection) kindPractices.remove("project"), pPractices); Iterator kinds = kindPractices.keySet().iterator(); while (kinds.hasNext()) { String kind = (String) kinds.next(); LOG.info(RuleMessages.getString("computation.kind", new Object[] { kind })); // sauvegarde du mode actuel de flush Session hibernateSession = ((SessionImpl) pSession).getSession(); FlushMode oldFlushMode = hibernateSession.getFlushMode(); // On ne traite pas les pratiques qui n'ont pas de composant associ // (elles n'ont pas de formule) if (kind.length() > 0) { try { // flush de la session hibernateSession.flush(); // le flush automatique est dsactiv pendant tout le calcul de chaque notes hibernateSession.setFlushMode(FlushMode.NEVER); // Recupration des enfants de bons niveaux... Collection children = AbstractComponentDAOImpl.getInstance().findProjectChildren(pSession, pProject, pAudit, Mapping.getComponentClass("component." + kind)); Iterator practices = ((Collection) kindPractices.get(kind)).iterator(); while (practices.hasNext()) { PracticeRuleBO practice = (PracticeRuleBO) practices.next(); LOG.info(RuleMessages.getString("computation.practice", new Object[] { practice.getName() })); PracticeResultBO practiceResult = (PracticeResultBO) pPractices.get(practice); // Vrification de la formule FormulaInterpreter interpreter = new FormulaInterpreter(); try { // Vrification de la syntaxe de la formule // un exception est leve si elle est incorrecte interpreter.checkSyntax(practice.getFormula()); // Calcul de notes pour chaque enfant computePracticeResults(pSession, pAudit, interpreter, practice, practiceResult, children); // Calcul de la note globale de la pratique computePracticeMark(practice, practiceResult); } catch (FormulaException e) { // Si une erreur se produit sur le calcul d'une formule // on stoppe le calcul pour cette pratique LOG.error(RuleMessages.getString("formula.error", new Object[] { practice.getName() }), e); } // Sauvegarde des rsultats de la pratique QualityResultDAOImpl.getInstance().save(pSession, practiceResult); } } catch (HibernateException e) { // Cette erreur est lie la gestion du flushmode, dans ce cas on se contente de remonter // une exception JRAF throw new JrafDaoException(e); } finally { // Remise du mode de flush au mode prcedent hibernateSession.setFlushMode(oldFlushMode); } } } }
From source file:org.squashtest.tm.service.internal.batchexport.ExportDao.java
License:Open Source License
private Session getStatelessSession() { Session s = em.unwrap(Session.class); s.setFlushMode(FlushMode.MANUAL); return s; }
From source file:org.unitime.timetable.action.CrossListsModifyAction.java
License:Open Source License
/** * Update the instructional offering// w w w. ja v a 2 s . c o m * @param request * @param frm */ private void doUpdate(HttpServletRequest request, CrossListsModifyForm frm) throws Exception { // Get the modified offering List ids = frm.getCourseOfferingIds(); String courseIds = Constants.arrayToStr(ids.toArray(), "", " "); String origCourseIds = frm.getOriginalOfferings(); // Get Offering CourseOfferingDAO cdao = new CourseOfferingDAO(); InstructionalOfferingDAO idao = new InstructionalOfferingDAO(); InstructionalOffering io = idao.get(frm.getInstrOfferingId()); Session hibSession = idao.getSession(); hibSession.setFlushMode(FlushMode.MANUAL); Transaction tx = null; HashMap saList = new HashMap(); List<CurriculumCourse> cc = new ArrayList<CurriculumCourse>(); try { tx = hibSession.beginTransaction(); StringTokenizer strTok = new StringTokenizer(origCourseIds); while (strTok.hasMoreTokens()) { String origCrs = strTok.nextToken(); // 1. For all deleted courses - create new offering and make 'not offered' if (courseIds.indexOf(origCrs) < 0) { Debug.debug("Course removed from offering: " + origCrs); // Create new instructional offering InstructionalOffering io1 = new InstructionalOffering(); CourseOffering co1 = cdao.get(new Long(origCrs.trim())); // Copy attributes of old instr offering - make not offered io1.setDemand(io.getDemand()); io1.setLimit(io.getLimit()); io1.setNotOffered(new Boolean(true)); io1.setSession(io.getSession()); io1.setByReservationOnly(io.getByReservationOnly()); // Copy attributes of old crs offering - set controlling CourseOffering co2 = (CourseOffering) co1.clone(); co2.setIsControl(new Boolean(true)); for (CurriculumCourse x : (List<CurriculumCourse>) hibSession .createQuery("from CurriculumCourse where course.uniqueId = :courseId") .setLong("courseId", co1.getUniqueId()).list()) { cc.add(x.clone(co2)); x.getClassification().getCourses().remove(x); hibSession.delete(x); } /* hibSession.saveOrUpdate(io1); hibSession.flush(); */ // Remove from original inst offr Set offerings = io.getCourseOfferings(); for (Iterator i = offerings.iterator(); i.hasNext();) { CourseOffering co3 = (CourseOffering) i.next(); if (co3.equals(co1)) { // Remove from Subject Area SubjectArea sa = co3.getSubjectArea(); sa.getCourseOfferings().remove(co1); hibSession.saveOrUpdate(sa); saList.put(sa.getSubjectAreaAbbreviation(), sa); } } // Delete old course offering io.removeCourseOffering(co1); Event.deleteFromEvents(hibSession, co1); Exam.deleteFromExams(hibSession, co1); String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value(); if (className != null && className.trim().length() > 0) { ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class .forName(className).newInstance()); removeAction.performExternalCourseOfferingRemoveAction(co1, hibSession); } hibSession.delete(co1); //io.setCourseOfferings(offerings); hibSession.saveOrUpdate(io); hibSession.flush(); // Add course to instructional offering co2.setInstructionalOffering(io1); io1.addTocourseOfferings(co2); // Update if (io1.getInstrOfferingPermId() == null) io1.generateInstrOfferingPermId(); hibSession.saveOrUpdate(io1); hibSession.flush(); hibSession.refresh(io); hibSession.refresh(io1); className = ApplicationProperty.ExternalActionInstructionalOfferingInCrosslistAdd.value(); if (className != null && className.trim().length() > 0) { ExternalInstructionalOfferingInCrosslistAddAction addAction = (ExternalInstructionalOfferingInCrosslistAddAction) (Class .forName(className).newInstance()); addAction.performExternalInstructionalOfferingInCrosslistAddAction(io1, hibSession); } } // 2. For all existing courses - update controlling attribute and reservation limits else { Debug.debug("Updating controlling course and course reservation: " + origCrs); // Update controlling course attribute CourseOffering co = cdao.get(new Long(origCrs)); if (frm.getCtrlCrsOfferingId().equals(co.getUniqueId())) co.setIsControl(new Boolean(true)); else co.setIsControl(new Boolean(false)); // Update course reservation int indx = frm.getIndex(origCrs); try { co.setReservation(ids.size() > 1 ? Integer.valueOf(frm.getLimits(indx)) : null); } catch (NumberFormatException e) { co.setReservation(null); } hibSession.saveOrUpdate(co); hibSession.flush(); hibSession.refresh(co); } } // 3. For all added courses - delete all preferences and change the instr offering id Vector addedOfferings = new Vector(); StringTokenizer strTok2 = new StringTokenizer(courseIds); while (strTok2.hasMoreTokens()) { String course = strTok2.nextToken(); // Course added to offering if (origCourseIds.indexOf(course) < 0) { Debug.debug("Course added to offering: " + course); CourseOffering co1 = cdao.get(new Long(course.trim())); InstructionalOffering io1 = co1.getInstructionalOffering(); SubjectArea sa = io1.getControllingCourseOffering().getSubjectArea(); Set offerings = io1.getCourseOfferings(); // Copy course offerings for (Iterator i = offerings.iterator(); i.hasNext();) { CourseOffering co2 = (CourseOffering) i.next(); SubjectArea sa2 = co2.getSubjectArea(); // Create a copy CourseOffering co3 = (CourseOffering) co2.clone(); if (frm.getCtrlCrsOfferingId().equals(co2.getUniqueId())) co3.setIsControl(new Boolean(true)); else co3.setIsControl(new Boolean(false)); for (CurriculumCourse x : (List<CurriculumCourse>) hibSession .createQuery("from CurriculumCourse where course.uniqueId = :courseId") .setLong("courseId", co2.getUniqueId()).list()) { cc.add(x.clone(co3)); x.getClassification().getCourses().remove(x); hibSession.delete(x); } addedOfferings.addElement(co3); int indx = frm.getIndex(course); try { co3.setReservation(Integer.valueOf(frm.getLimits(indx))); } catch (NumberFormatException e) { co3.setReservation(null); } // Remove from collection //i.remove(); sa2.getCourseOfferings().remove(co2); hibSession.saveOrUpdate(sa2); saList.put(sa2.getSubjectAreaAbbreviation(), sa2); // Delete course offering io1.removeCourseOffering(co2); Event.deleteFromEvents(hibSession, co2); Exam.deleteFromExams(hibSession, co2); String className = ApplicationProperty.ExternalActionCourseOfferingRemove.value(); if (className != null && className.trim().length() > 0) { ExternalCourseOfferingRemoveAction removeAction = (ExternalCourseOfferingRemoveAction) (Class .forName(className).newInstance()); removeAction.performExternalCourseOfferingRemoveAction(co2, hibSession); } hibSession.delete(co2); hibSession.flush(); //hibSession.refresh(sa2); } //io1.setCourseOfferings(offerings); //hibSession.saveOrUpdate(io1); Event.deleteFromEvents(hibSession, io1); Exam.deleteFromExams(hibSession, io1); hibSession.delete(io1); hibSession.flush(); hibSession.saveOrUpdate(sa); saList.put(sa.getSubjectAreaAbbreviation(), sa); //hibSession.refresh(sa); } } hibSession.flush(); // Update Offering - Added Offerings for (int i = 0; i < addedOfferings.size(); i++) { CourseOffering co3 = (CourseOffering) addedOfferings.elementAt(i); co3.setInstructionalOffering(io); io.addTocourseOfferings(co3); hibSession.saveOrUpdate(co3); hibSession.flush(); hibSession.refresh(co3); hibSession.saveOrUpdate(io); } for (CurriculumCourse x : cc) hibSession.saveOrUpdate(x); // Update managing department on all classes Department dept = io.getControllingCourseOffering().getDepartment(); Set cfgs = io.getInstrOfferingConfigs(); for (Iterator iterCfg = cfgs.iterator(); iterCfg.hasNext();) { InstrOfferingConfig cfg = (InstrOfferingConfig) iterCfg.next(); Set subparts = cfg.getSchedulingSubparts(); for (Iterator iterSbp = subparts.iterator(); iterSbp.hasNext();) { SchedulingSubpart subpart = (SchedulingSubpart) iterSbp.next(); Set classes = subpart.getClasses(); for (Iterator iterCls = classes.iterator(); iterCls.hasNext();) { Class_ cls = (Class_) iterCls.next(); // Only change departmental class managing dept and not externally managed if (!cls.getManagingDept().isExternalManager()) { cls.setManagingDept(dept); hibSession.saveOrUpdate(cls); } } } } ChangeLog.addChange(hibSession, sessionContext, io, ChangeLog.Source.CROSS_LIST, ChangeLog.Operation.UPDATE, io.getControllingCourseOffering().getSubjectArea(), null); tx.commit(); hibSession.flush(); hibSession.clear(); hibSession.refresh(io); // Refresh objects for (Iterator i1 = io.getInstrOfferingConfigs().iterator(); i1.hasNext();) { InstrOfferingConfig cfg = (InstrOfferingConfig) i1.next(); for (Iterator i2 = cfg.getSchedulingSubparts().iterator(); i2.hasNext();) { SchedulingSubpart ss = (SchedulingSubpart) i2.next(); for (Iterator i3 = ss.getClasses().iterator(); i3.hasNext();) { Class_ c = (Class_) i3.next(); hibSession.refresh(c); } hibSession.refresh(ss); } } Set keys = saList.keySet(); for (Iterator i1 = keys.iterator(); i1.hasNext();) { hibSession.refresh(saList.get(i1.next())); } String className = ApplicationProperty.ExternalActionCourseCrosslist.value(); if (className != null && className.trim().length() > 0) { ExternalCourseCrosslistAction addAction = (ExternalCourseCrosslistAction) (Class.forName(className) .newInstance()); addAction.performExternalCourseCrosslistAction(io, hibSession); } } catch (Exception e) { Debug.error(e); try { if (tx != null && tx.isActive()) tx.rollback(); } catch (Exception e1) { } throw e; } }
From source file:org.unitime.timetable.solver.instructor.InstructorSchedulingDatabaseLoader.java
License:Apache License
public void load() throws Exception { ApplicationProperties.setSessionId(iSessionId); org.hibernate.Session hibSession = null; Transaction tx = null;/*from w ww . j av a 2s . com*/ try { hibSession = TimetableManagerDAO.getInstance().createNewSession(); hibSession.setCacheMode(CacheMode.IGNORE); hibSession.setFlushMode(FlushMode.COMMIT); tx = hibSession.beginTransaction(); load(hibSession); tx.commit(); } catch (Exception e) { iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e); tx.rollback(); } finally { // here we need to close the session since this code may run in a separate thread if (hibSession != null && hibSession.isOpen()) hibSession.close(); } }
From source file:org.webical.web.util.WriteableOpenSessionInViewFilter.java
License:Open Source License
@Override protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { log.debug("returning session"); /* Checks for a Session currently bound to the thread and creates one if not found */ Session session = SessionFactoryUtils.getSession(sessionFactory, true); /* Makes the Session writable */ session.setFlushMode(FlushMode.AUTO); return session; }