List of usage examples for org.hibernate Session setDefaultReadOnly
void setDefaultReadOnly(boolean readOnly);
From source file:at.molindo.esi4j.module.hibernate.HibernateEntityResolver.java
License:Apache License
public void openResolveSession() { Session session = _localSession.get(); if (session != null) { log.warn("session already open, now closing first"); closeResolveSession();//from w w w . ja v a 2 s .c om session = null; } session = getNewSession(getSessionFactory()); session.setDefaultReadOnly(true); session.setCacheMode(CacheMode.GET); session.setFlushMode(FlushMode.MANUAL); session.beginTransaction(); _localSession.set(session); }
From source file:com.astonish.dropwizard.routing.hibernate.RoutingUnitOfWorkRequestDispatcher.java
License:Apache License
/** * Configures the session./* w w w.j av a 2 s. co m*/ * @param session * the session */ private void configureSession(Session session) { session.setDefaultReadOnly(unitOfWork.readOnly()); session.setCacheMode(unitOfWork.cacheMode()); session.setFlushMode(unitOfWork.flushMode()); }
From source file:com.mercatis.lighthouse3.persistence.commons.hibernate.UnitOfWorkImplementation.java
License:Apache License
/** * Returns the current hibernate session for the unit of work. * //from www .ja va 2 s . c om * @return the hibernate session */ public Session getCurrentSession() { Session session = threadLocalSessions.get(); if (session == null) { try { if (log.isDebugEnabled()) { log.debug("UnitOfWork: Open Session, SessionFactory: " + System.identityHashCode(this.getSessionFactory())); } session = this.getSessionFactory().openSession(); session.setDefaultReadOnly(true); if (!session.getTransaction().isActive()) session.beginTransaction(); threadLocalSessions.set(session); } catch (Exception e1) { try { session.close(); threadLocalSessions.set(null); } catch (Exception e2) { log.error(e2.getMessage(), e2); } throw new PersistenceException("Could not open new session", e1); } } if (log.isDebugEnabled()) { log.debug("UnitOfWork: Providing Session: " + System.identityHashCode(session)); } return session; }
From source file:com.nominanuda.hibernate.HibernateQuerableStore.java
License:Apache License
public DataArray query(String hql, DataObject params, int start, int count, String viewName) throws Exception { Session session = null; Transaction tx = null;/*from ww w .j a v a 2 s .c om*/ try { session = sessionFactory.openSession(); session.setDefaultReadOnly(true); tx = session.beginTransaction(); Query q = session.createQuery(hql).setReadOnly(true).setFirstResult(start).setMaxResults(count); for (String k : params.getKeys()) { bind(q, k, params.get(k)); } List<?> l = q.list(); return render(l, viewName); } catch (Exception e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { if (tx != null && !tx.wasRolledBack()) { tx.rollback(); } if (session != null) { session.close(); } } }
From source file:com.peterphi.std.guice.hibernate.module.TransactionMethodInterceptor.java
License:Apache License
/** * Make the session (and the underlying {@link java.sql.Connection} read only * * @param session// w w w .ja v a 2s. c om */ private void makeReadOnly(final Session session) { session.setDefaultReadOnly(true); session.setFlushMode(FlushMode.MANUAL); // Make the Connection read only session.doWork(SetJDBCConnectionReadOnlyWork.READ_ONLY); }
From source file:com.yahoo.elide.datastores.hibernate3.HibernateStore.java
License:Apache License
@Override public DataStoreTransaction beginReadTransaction() { Session session = sessionFactory.getCurrentSession(); Preconditions.checkNotNull(session); session.beginTransaction();//from w ww. j a v a2 s. co m session.setDefaultReadOnly(true); return transactionSupplier.get(session, isScrollEnabled, scrollMode); }
From source file:de.innovationgate.webgate.api.jdbc.filehandling.CS5P4FileHandling.java
License:Open Source License
@Override public long dailyFileMaintenance(Logger log) throws WGAPIException { Session session = getParent().getSession(); try {/*ww w. j a v a 2 s .c o m*/ session.setDefaultReadOnly(false); long freedMemory = 0; int deletedDuplicates = 0; // Remove duplicate file contents String hql = "select cfc.checksumSha512 as checksum from ContentFileContent as cfc group by cfc.checksumSha512 having count(*) > 1"; @SuppressWarnings("unchecked") Iterator<String> duplicateChecksums = session.createQuery(hql).iterate(); while (duplicateChecksums.hasNext()) { String duplicaceChecksum = duplicateChecksums.next(); hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 = :checksum order by cfc.ordinalnr asc"; Query q = session.createQuery(hql); q.setParameter("checksum", duplicaceChecksum); @SuppressWarnings("unchecked") Iterator<String> duplicateIds = q.iterate(); if (!duplicateIds.hasNext()) { // Just in case continue; } // Skip the first one. That is the one that will be kept and constantly retrieved duplicateIds.next(); // Delete the other duplicates while (duplicateIds.hasNext()) { String id = duplicateIds.next(); ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id); if (cfc != null) { deletedDuplicates++; freedMemory += cfc.getSize(); session.setReadOnly(cfc, false); // Delete data entities via HQL to prevent loading them hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc"; Query deleteQ = session.createQuery(hql); deleteQ.setParameter("cfc", cfc); deleteQ.executeUpdate(); session.delete(cfc); getParent().commitHibernateTransaction(); } } Hibernate.close(duplicateIds); } Hibernate.close(duplicateChecksums); // Remove unused file contents long deletedUnusedFiles = 0; hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 not in (select distinct cfm.checksumSha512 from ContentFileMeta as cfm where cfm.checksumSha512 is not null) and cfc.checksumSha512 not in (select distinct cfd.derivateSha512 from ContentFileDerivate as cfd)"; @SuppressWarnings("unchecked") Iterator<String> obsoleteIds = session.createQuery(hql).iterate(); while (obsoleteIds.hasNext()) { String id = obsoleteIds.next(); ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id); if (cfc != null) { deletedUnusedFiles++; freedMemory += cfc.getSize(); session.setReadOnly(cfc, false); // Delete data entities via HQL to prevent loading them hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc"; Query deleteQ = session.createQuery(hql); deleteQ.setParameter("cfc", cfc); deleteQ.executeUpdate(); session.delete(cfc); //log.info("Deleted file contents " + cfc.getChecksumSha512() + " ordinal nr " + cfc.getOrdinalnr()); getParent().commitHibernateTransaction(); } } Hibernate.close(obsoleteIds); // Remove unused derivates of old CS5P4 style. Corresponding derivate data is deleted in the next run. hql = "select cfd.id as id from ContentFileDerivate as cfd where cfd.parentSha512 not in (select distinct cfc.checksumSha512 from ContentFileContent as cfc)"; @SuppressWarnings("unchecked") Iterator<String> obsoleteDerivateIds = session.createQuery(hql).iterate(); while (obsoleteDerivateIds.hasNext()) { String id = obsoleteDerivateIds.next(); ContentFileDerivate cfd = (ContentFileDerivate) session.get(ContentFileDerivate.class, id); if (cfd != null) { session.setReadOnly(cfd, false); session.delete(cfd); getParent().commitHibernateTransaction(); } } Hibernate.close(obsoleteDerivateIds); String freedMemoryText; if (deletedDuplicates > 0 || deletedUnusedFiles > 0) { if (freedMemory > 1024 * 1024) { freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory / 1024 / 1024) + " MB of file storage"; } else { freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory) + " Bytes of file storage"; } log.info("Maintenance on content store of app/plugin '" + getParent().getDb().getDbReference() + "': Deleted " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedDuplicates) + " duplicates and " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedUnusedFiles) + " unused file contents freeing " + freedMemoryText); } return freedMemory; } catch (Throwable e) { try { session.getTransaction().rollback(); } catch (Exception e2) { } throw new WGBackendException("Exception running daily maintenance", e); } finally { session.setDefaultReadOnly(true); } }
From source file:de.innovationgate.webgate.api.jdbc.filehandling.CS5P5FileHandling.java
License:Open Source License
@Override public long dailyFileMaintenance(Logger log) throws WGAPIException { Session session = getParent().getSession(); try {/*w w w .j a va 2 s. com*/ session.setDefaultReadOnly(false); long freedMemory = 0; int deletedDuplicates = 0; // Remove duplicate file contents String hql = "select cfc.checksumSha512 as checksum from ContentFileContent as cfc group by cfc.checksumSha512 having count(*) > 1"; @SuppressWarnings("unchecked") Iterator<String> duplicateChecksums = session.createQuery(hql).iterate(); while (duplicateChecksums.hasNext()) { String duplicaceChecksum = duplicateChecksums.next(); hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 = :checksum order by cfc.ordinalnr asc"; Query q = session.createQuery(hql); q.setParameter("checksum", duplicaceChecksum); @SuppressWarnings("unchecked") Iterator<String> duplicateIds = q.iterate(); if (!duplicateIds.hasNext()) { // Just in case continue; } // Skip the first one. That is the one that will be kept and // constantly retrieved duplicateIds.next(); // Delete the other duplicates while (duplicateIds.hasNext()) { String id = duplicateIds.next(); ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id); if (cfc != null) { deletedDuplicates++; freedMemory += cfc.getSize(); session.setReadOnly(cfc, false); // Delete data entities via HQL to prevent loading them hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc"; Query deleteQ = session.createQuery(hql); deleteQ.setParameter("cfc", cfc); deleteQ.executeUpdate(); session.delete(cfc); getParent().commitHibernateTransaction(); } } Hibernate.close(duplicateIds); } Hibernate.close(duplicateChecksums); // Remove unused file contents, not used on attachments, derivates // or binary extension data long deletedUnusedFiles = 0; hql = "select cfc.id as id from ContentFileContent as cfc where cfc.checksumSha512 not in (select distinct cfm.checksumSha512 from ContentFileMeta as cfm where cfm.checksumSha512 is not null) and cfc.checksumSha512 not in (select distinct cfd.derivateSha512 from ContentFileDerivate as cfd) and cfc.checksumSha512 not in (select distinct ext.binarySha512 from ExtensionData as ext where ext.type=7)"; @SuppressWarnings("unchecked") Iterator<String> obsoleteIds = session.createQuery(hql).iterate(); while (obsoleteIds.hasNext()) { String id = obsoleteIds.next(); ContentFileContent cfc = (ContentFileContent) session.get(ContentFileContent.class, id); if (cfc != null) { deletedUnusedFiles++; freedMemory += cfc.getSize(); session.setReadOnly(cfc, false); // Delete data entities via HQL to prevent loading them hql = "delete ContentFileContentPart cfp where cfp.fileContents=:cfc"; Query deleteQ = session.createQuery(hql); deleteQ.setParameter("cfc", cfc); deleteQ.executeUpdate(); session.delete(cfc); // log.info("Deleted file contents " + // cfc.getChecksumSha512() + " ordinal nr " + // cfc.getOrdinalnr()); getParent().commitHibernateTransaction(); } } Hibernate.close(obsoleteIds); // Remove unused derivates of old CS5P4 style. Corresponding // derivate data is deleted in the next run. hql = "select cfd.id as id from ContentFileDerivate as cfd where cfd.parentMeta is null and cfd.parentSha512 not in (select distinct cfc.checksumSha512 from ContentFileContent as cfc)"; @SuppressWarnings("unchecked") Iterator<String> obsoleteDerivateIds = session.createQuery(hql).iterate(); while (obsoleteDerivateIds.hasNext()) { String id = obsoleteDerivateIds.next(); ContentFileDerivate cfd = (ContentFileDerivate) session.get(ContentFileDerivate.class, id); if (cfd != null) { session.setReadOnly(cfd, false); session.delete(cfd); getParent().commitHibernateTransaction(); } } Hibernate.close(obsoleteDerivateIds); String freedMemoryText; if (deletedDuplicates > 0 || deletedUnusedFiles > 0) { if (freedMemory > 1024 * 1024) { freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory / 1024 / 1024) + " MB of file storage"; } else { freedMemoryText = WGUtils.DECIMALFORMAT_STANDARD.format(freedMemory) + " Bytes of file storage"; } log.info("Maintenance on content store of app/plugin '" + getParent().getDb().getDbReference() + "': Deleted " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedDuplicates) + " duplicates and " + WGUtils.DECIMALFORMAT_STANDARD.format(deletedUnusedFiles) + " unused file contents freeing " + freedMemoryText); } return freedMemory; } catch (Throwable e) { try { session.getTransaction().rollback(); } catch (Exception e2) { } throw new WGBackendException("Exception running daily maintenance", e); } finally { session.setDefaultReadOnly(true); } }
From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java
License:Open Source License
/** * @throws WGUnavailableException /*from w w w. j a v a 2 s . co m*/ * @throws WGAPIException * @see de.innovationgate.webgate.api.WGDatabaseCore#openSession(String, * String) */ public WGUserAccess openSession(AuthenticationSession authSession, Object pwd, boolean master) throws WGAPIException { try { // Hibernate login Session session = _sessionBuilder.openSession(); // Connection conn = session.connection(); // conn.setAutoCommit(true); //Problematic with DBCP? session.setFlushMode(FlushMode.COMMIT); if (_saveIsolationActive) { session.setDefaultReadOnly(true); } getSessionStatus().setSession(session); if (!session.isOpen()) { throw new WGUnavailableException(_db, "Unable to connect to hibernate session"); } // special handling if loadbalancing is enabled if (hasFeature(WGDatabase.FEATURE_LOADBALANCE)) { // set all connections to readonly except master sessions and if // update is in progress final boolean readOnly = (master ? false : !isUpdateInProgress(authSession.getDistinguishedName())); try { session.doWork(new Work() { public void execute(Connection connection) throws SQLException { connection.setReadOnly(readOnly); } }); } catch (HibernateException e) { throw new WGBackendException("Unable to set readonly flag on connection.", e); } } if (getTransactionMode() != WGSessionContext.TRANSACTION_MODE_MANUAL) { session.beginTransaction(); } if (master) { // Master login always has manager access return new WGUserAccess(WGDatabase.MASTER_USERNAME, WGDatabase.ACCESSLEVEL_MANAGER); } // Determine access WGUserDetails userDetails; try { userDetails = _db.defaultBuildUserDetails(authSession); } catch (WGBackendException e) { try { closeSession(); } catch (WGBackendException e1) { WGFactory.getLogger().error(e1); } throw e; } if (userDetails.getAccessLevel() <= WGDatabase.ACCESSLEVEL_NOACCESS) { try { closeSession(); } catch (WGBackendException e) { WGFactory.getLogger().error(e); } } return userDetails; } catch (HibernateException e) { try { closeSession(); } catch (WGBackendException e1) { WGFactory.getLogger().error(e1); } throw new WGUnavailableException(_db, "Error opening hibernate session", e); } }
From source file:dk.dma.ais.abnormal.event.db.jpa.JpaEventRepository.java
License:Open Source License
private Session getSession() { Session session = sessionFactory.openSession(); LOG.debug("Database session acquired: " + session); if (readonly) { session.setDefaultReadOnly(true); }/* w w w. j a va 2s . c o m*/ return session; }