List of usage examples for org.hibernate Session setFlushMode
@Deprecated
void setFlushMode(FlushMode flushMode);
From source file:com.rdsic.pcm.common.HibernateUtil.java
public static Session currentSession(String cfgFile) { initSessionFactory(cfgFile);//from w ww .ja v a2 s . c om Session s = (Session) session.get(); if ((s == null) || (!s.isConnected())) { s = sessionFactory.openSession(); s.setFlushMode(FlushMode.COMMIT); s.setCacheMode(CacheMode.IGNORE); session.set(s); } return s; }
From source file:com.smi.travel.common.SessionInView.java
@Override protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); session.setFlushMode(FlushMode.AUTO); return session; }
From source file:com.springsource.insight.samples.rest.RestfulRepositoryImplTest.java
License:Apache License
protected void manuallyStartDaoSession() { // simulate open session in view final SessionFactory sessFac = getSessionFactory(); if (TransactionSynchronizationManager.hasResource(sessFac)) { // Do not modify the Session: just set the participate flag. _txParticipating = true;/* w w w .j a va2 s .co m*/ } else { // NOTE: the session factory interceptor is overridden by an empty one, because the // real interceptor may not function correctly in this test-specific setup. final Session session = SessionFactoryUtils.getSession(sessFac, EmptyInterceptor.INSTANCE, null); session.setFlushMode(FlushMode.AUTO); TransactionSynchronizationManager.bindResource(sessFac, new SessionHolder(session)); logger.info("Started transaction context"); } }
From source file:com.syncnapsis.utils.SessionFactoryUtil.java
License:Open Source License
/** * Open a Session that is bound to the {@link TransactionSynchronizationManager}.<br> * The Session will be configured with {@link FlushMode#COMMIT} * /*from w ww . j av a 2s. co m*/ * @param useSessionHolder - select wether to use a SessionHolder for binding or not * @return the session opened */ public Session openBoundSession() { Session session = sessionFactory.openSession(); session.setFlushMode(FlushMode.COMMIT); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); return session; }
From source file:com.tysanclan.site.projectewok.dataaccess.EwokHibernateDAO.java
License:Open Source License
/** * @return The Session for this factory/*www. j a v a 2s. co m*/ */ @Override public Session getSession() { Session session = sessionFactory.getCurrentSession(); session.setFlushMode(FlushMode.COMMIT); return session; }
From source file:com.vmware.bdd.dal.DAL.java
License:Open Source License
/** * Helper routine for wrapping a piece of code in a Hibernate transaction. * * @param obj -- the body of the transaction. * @param readOnly -- true if the writes are to be disallowed * @param retriesLeft -- the max number of times to retry on lock-acquisition exceptions. * 0 if retries are to be disallowed./* w w w .j a va 2 s . co m*/ **/ @SuppressWarnings("deprecation") private static <T> T inTransactionDoWork(Saveable<T> obj, boolean readOnly, int retriesLeft) { T retval; while (true) { Session sn = getSession(); Transaction tx = null; FlushMode flushMode = null; boolean doRndRollback = ConfigInfo.isDebugEnabled() && stressTxnRollback && (rnd.nextInt() % 5) == 0; AuAssert.check(!isInTransaction()); // Disallow nesting for now. try { tx = sn.beginTransaction(); if (readOnly && tx != null) { flushMode = sn.getFlushMode(); sn.setFlushMode(FlushMode.MANUAL); } sn.connection().setReadOnly(readOnly); retval = obj.body(); if (doRndRollback) { logger.warn("randomly rollback the transaction"); throw new LockAcquisitionException("Random Rollback", new SQLException("Random Rollback")); } if (flushMode != null) { sn.setFlushMode(flushMode); } tx.commit(); break; // must come right after commit } catch (Throwable ex) { if (tx != null) { if (flushMode != null) { sn.setFlushMode(flushMode); } tx.rollback(); flushTransactionCallbacks(false); } // Strip off the BddException wrapper if a callee added it. Throwable realEx = (ex instanceof BddException) ? ex.getCause() : ex; if (isRetryable(realEx)) { if (retriesLeft > 0) { if (!doRndRollback) { retriesLeft--; reportRetry(retriesLeft, realEx); } } else { throw TxRetryException.wrap(realEx, doRndRollback); } } else if (isUniqViolation(realEx)) { throw UniqueConstraintViolationException.wrap((ConstraintViolationException) realEx); } else { throw BddException.wrapIfNeeded(ex, "Exception in a DAL transaction"); } } } flushTransactionCallbacks(true); return retval; }
From source file:com.wanggang.web.filters.OpenSessionInViewFilter.java
License:Apache License
/** * Get a Session for the SessionFactory that this filter uses. * Note that this just applies in single session mode! * <p>The default implementation delegates to the * <code>SessionFactoryUtils.getSession</code> method and * sets the <code>Session</code>'s flush mode to "MANUAL". * <p>Can be overridden in subclasses for creating a Session with a * custom entity interceptor or JDBC exception translator. * @param sessionFactory the SessionFactory that this filter uses * @return the Session to use//from www . j a v a 2s .co m * @throws DataAccessResourceFailureException if the Session could not be created * @see org.springframework.orm.hibernate3.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.hibernate.FlushMode#MANUAL */ protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); FlushMode flushMode = getFlushMode(); if (flushMode != null) { session.setFlushMode(flushMode); } return session; }
From source file:com.wideplay.warp.persist.hibernate.HibernateLocalTxnInterceptor.java
License:Apache License
public Object invoke(MethodInvocation methodInvocation) throws Throwable { Session session = sessionProvider.get(); //allow silent joining of enclosing transactional methods (NOTE: this ignores the current method's txn-al settings) if (session.getTransaction().isActive()) return methodInvocation.proceed(); //read out transaction settings Transactional transactional = readTransactionMetadata(methodInvocation); //read-only txn? FlushMode savedFlushMode = FlushMode.AUTO; if (TransactionType.READ_ONLY.equals(transactional.type())) session.setFlushMode(FlushMode.MANUAL); try {/*from www .j a va 2s . c om*/ //no transaction already started, so start one and enforce its semantics Transaction txn = session.beginTransaction(); Object result; try { result = methodInvocation.proceed(); } catch (Exception e) { //commit transaction only if rollback didnt occur if (rollbackIfNecessary(transactional, e, txn)) txn.commit(); //propagate whatever exception is thrown anyway throw e; } //everything was normal so commit the txn (do not move into try block as it interferes with the advised method's throwing semantics) Exception commitException = null; try { txn.commit(); } catch (RuntimeException re) { txn.rollback(); commitException = re; } //propagate anyway if (null != commitException) throw commitException; //or return result return result; } finally { //if read-only txn, then restore flushmode, default is automatic flush if (TransactionType.READ_ONLY.equals(transactional.type())) session.setFlushMode(savedFlushMode); } }
From source file:com.xpn.xwiki.internal.store.hibernate.HibernateStore.java
License:Open Source License
/** * @return the current {@link Session} or null *///from www.j ava 2s . c om public Session getCurrentSession() { ExecutionContext context = this.execution.getContext(); if (context != null) { Session session = (Session) context.getProperty(CONTEXT_SESSION); // Make sure we are in this mode try { if (session != null) { session.setFlushMode(FlushMode.COMMIT); } } catch (org.hibernate.SessionException ex) { session = null; } return session; } return null; }
From source file:com.xpn.xwiki.store.XWikiHibernateStore.java
License:Open Source License
public void saveXWikiDoc(XWikiDocument doc, XWikiContext context, boolean bTransaction) throws XWikiException { MonitorPlugin monitor = Util.getMonitorPlugin(context); try {//from w w w. j av a2 s . com // Start monitoring timer if (monitor != null) { monitor.startTimer("hibernate"); } doc.setStore(this); // Make sure the database name is stored doc.getDocumentReference().setWikiReference(new WikiReference(context.getDatabase())); if (bTransaction) { checkHibernate(context); SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context); bTransaction = beginTransaction(sfactory, context); } Session session = getSession(context); session.setFlushMode(FlushMode.COMMIT); // These informations will allow to not look for attachments and objects on loading doc.setElement(XWikiDocument.HAS_ATTACHMENTS, (doc.getAttachmentList().size() != 0)); doc.setElement(XWikiDocument.HAS_OBJECTS, (doc.getXObjects().size() != 0)); // Let's update the class XML since this is the new way to store it // TODO If all the properties are removed, the old xml stays? BaseClass bclass = doc.getXClass(); if (bclass != null) { if (bclass.getFieldList().size() > 0) { doc.setXClassXML(bclass.toXMLString()); } else { doc.setXClassXML(""); } } if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) { saveAttachmentList(doc, context, false); } // Handle the latest text file if (doc.isContentDirty() || doc.isMetaDataDirty()) { Date ndate = new Date(); doc.setDate(ndate); if (doc.isContentDirty()) { doc.setContentUpdateDate(ndate); doc.setContentAuthorReference(doc.getAuthorReference()); } doc.incrementVersion(); if (context.getWiki().hasVersioning(context)) { context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context); } doc.setContentDirty(false); doc.setMetaDataDirty(false); } else { if (doc.getDocumentArchive() != null) { // Let's make sure we save the archive if we have one // This is especially needed if we load a document from XML if (context.getWiki().hasVersioning(context)) { context.getWiki().getVersioningStore().saveXWikiDocArchive(doc.getDocumentArchive(), false, context); } } else { // Make sure the getArchive call has been made once // with a valid context try { if (context.getWiki().hasVersioning(context)) { doc.getDocumentArchive(context); } } catch (XWikiException e) { // this is a non critical error } } } // Verify if the document already exists Query query = session .createQuery("select xwikidoc.id from XWikiDocument as xwikidoc where xwikidoc.id = :id"); query.setLong("id", doc.getId()); if (query.uniqueResult() == null) { session.save(doc); } else { session.update(doc); // TODO: this is slower!! How can it be improved? // session.saveOrUpdate(doc); } // Remove objects planned for removal if (doc.getXObjectsToRemove().size() > 0) { for (BaseObject removedObject : doc.getXObjectsToRemove()) { deleteXWikiObject(removedObject, context, false); } doc.setXObjectsToRemove(new ArrayList<BaseObject>()); } if (bclass != null) { bclass.setDocumentReference(doc.getDocumentReference()); // Store this XWikiClass in the context so that we can use it in case of recursive usage of classes context.addBaseClass(bclass); // Update instances of the class, in case some properties changed their storage type // In case the current document has both a class and instances of that class, we have to take care // not to insert duplicate entities in the session Map<Integer, BaseObject> localClassObjects = new HashMap<Integer, BaseObject>(); if (doc.hasElement(XWikiDocument.HAS_OBJECTS) && doc.getXObjects(doc.getDocumentReference()) != null) { for (BaseObject obj : doc.getXObjects(doc.getDocumentReference())) { if (obj != null) { localClassObjects.put(obj.getId(), obj); } } } for (PropertyClass prop : (Collection<PropertyClass>) bclass.getFieldList()) { // migrate values of list properties if (prop instanceof StaticListClass || prop instanceof DBListClass) { ListClass lc = (ListClass) prop; String[] classes = { DBStringListProperty.class.getName(), StringListProperty.class.getName(), StringProperty.class.getName() }; // @see ListClass#newProperty() for (int i = 0; i < classes.length; i++) { String oldclass = classes[i]; if (!oldclass.equals(lc.newProperty().getClass().getName())) { Query q = session .createQuery("select p from " + oldclass + " as p, BaseObject as o" + " where o.className=? and p.id=o.id and p.name=?") .setString(0, bclass.getName()).setString(1, lc.getName()); for (Iterator it = q.list().iterator(); it.hasNext();) { BaseProperty lp = (BaseProperty) it.next(); BaseProperty lp1 = lc.newProperty(); lp1.setId(lp.getId()); lp1.setName(lp.getName()); if (lc.isMultiSelect()) { List tmp; if (lp.getValue() instanceof List) { tmp = (List) lp.getValue(); } else { tmp = new ArrayList<String>(1); tmp.add(lp.getValue()); } lp1.setValue(tmp); } else { Object tmp = lp.getValue(); if (tmp instanceof List && ((List) tmp).size() > 0) { tmp = ((List) tmp).get(0); } lp1.setValue(tmp); } session.delete(lp); session.save(lp1); } } } } // migrate values of list properties else if (prop instanceof NumberClass) { NumberClass nc = (NumberClass) prop; // @see NumberClass#newProperty() String[] classes = { IntegerProperty.class.getName(), LongProperty.class.getName(), FloatProperty.class.getName(), DoubleProperty.class.getName() }; for (int i = 0; i < classes.length; i++) { String oldclass = classes[i]; if (!oldclass.equals(nc.newProperty().getClass().getName())) { Query q = session .createQuery("select p from " + oldclass + " as p, BaseObject as o" + " where o.className=?" + " and p.id=o.id and p.name=?") .setString(0, bclass.getName()).setString(1, nc.getName()); for (BaseProperty np : (List<BaseProperty>) q.list()) { BaseProperty np1 = nc.newProperty(); np1.setId(np.getId()); np1.setName(np.getName()); if (nc.getNumberType().equals("integer")) { np1.setValue(Integer.valueOf(((Number) np.getValue()).intValue())); } else if (nc.getNumberType().equals("float")) { np1.setValue(Float.valueOf(((Number) np.getValue()).floatValue())); } else if (nc.getNumberType().equals("double")) { np1.setValue(Double.valueOf(((Number) np.getValue()).doubleValue())); } else if (nc.getNumberType().equals("long")) { np1.setValue(Long.valueOf(((Number) np.getValue()).longValue())); } session.delete(np); session.save(np1); } } } } else { // General migration of properties Query q = session.createQuery("select p from BaseProperty as p, BaseObject as o" + " where o.className=? and p.id=o.id and p.name=? and p.classType <> ?"); q.setString(0, bclass.getName()); q.setString(1, prop.getName()); q.setString(2, prop.newProperty().getClassType()); @SuppressWarnings("unchecked") List<BaseProperty> brokenProperties = q.list(); for (BaseProperty brokenProperty : brokenProperties) { BaseProperty newProperty = prop.fromString(brokenProperty.toText()); BaseObject localObject = localClassObjects.get(brokenProperty.getId()); if (localObject != null) { BaseProperty currentProperty = (BaseProperty) localObject.get(prop.getName()); if (currentProperty != null) { newProperty = prop.fromString(currentProperty.toText()); if (newProperty != null) { localObject.put(prop.getName(), newProperty); } else { localObject.put(prop.getName(), brokenProperty); } } } if (newProperty == null) { log.warn("Incompatible data migration when changing field {} of class {}", prop.getName(), prop.getClassName()); continue; } newProperty.setId(brokenProperty.getId()); session.delete(brokenProperty); session.save(newProperty); } } } } if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) { // TODO: Delete all objects for which we don't have a name in the Map for (List<BaseObject> objects : doc.getXObjects().values()) { for (BaseObject obj : objects) { if (obj != null) { obj.setDocumentReference(doc.getDocumentReference()); /* If the object doesn't have a GUID, create it before saving */ if (StringUtils.isEmpty(obj.getGuid())) { obj.setGuid(UUID.randomUUID().toString()); } saveXWikiCollection(obj, context, false); } } } } if (context.getWiki().hasBacklinks(context)) { saveLinks(doc, context, true); } if (bTransaction) { endTransaction(context, true); } doc.setNew(false); // We need to ensure that the saved document becomes the original document doc.setOriginalDocument(doc.clone()); } catch (Exception e) { Object[] args = { this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) }; throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC, "Exception while saving document {0}", e, args); } finally { try { if (bTransaction) { endTransaction(context, false); } } catch (Exception e) { } // End monitoring timer if (monitor != null) { monitor.endTimer("hibernate"); } } }