List of usage examples for org.hibernate FlushMode COMMIT
FlushMode COMMIT
To view the source code for org.hibernate FlushMode COMMIT.
Click Source Link
From source file:org.apereo.portal.events.handlers.db.JpaPortalEventStore.java
License:Apache License
@Override @RawEventsTransactional/* w w w.ja va 2s .c o m*/ public boolean aggregatePortalEvents(DateTime startTime, DateTime endTime, int maxEvents, Function<PortalEvent, Boolean> handler) { final Session session = this.getEntityManager().unwrap(Session.class); session.setFlushMode(FlushMode.COMMIT); final org.hibernate.Query query = session.createQuery(this.selectUnaggregatedQuery); query.setParameter(this.startTimeParameter.getName(), startTime); query.setParameter(this.endTimeParameter.getName(), endTime); if (maxEvents > 0) { query.setMaxResults(maxEvents); } int resultCount = 0; for (final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); results.next();) { final PersistentPortalEvent persistentPortalEvent = (PersistentPortalEvent) results.get(0); final PortalEvent portalEvent; try { portalEvent = this.toPortalEvent(persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType()); } catch (RuntimeException e) { this.logger.warn("Failed to convert PersistentPortalEvent to PortalEvent: " + persistentPortalEvent, e); //Mark the event as error and store the mark to prevent trying to reprocess the broken event data persistentPortalEvent.setErrorAggregating(true); session.persist(persistentPortalEvent); continue; } try { final Boolean eventHandled = handler.apply(portalEvent); if (!eventHandled) { this.logger.debug("Aggregation stop requested before processing event {}", portalEvent); return false; } //Mark the event as aggregated and store the mark persistentPortalEvent.setAggregated(true); session.persist(persistentPortalEvent); //periodic flush and clear of session to manage memory demands if (++resultCount % this.flushPeriod == 0) { this.logger.debug("Aggregated {} events, flush and clear {} EntityManager.", resultCount, PERSISTENCE_UNIT_NAME); session.flush(); session.clear(); } } catch (Exception e) { this.logger.warn("Failed to aggregate portal event: " + persistentPortalEvent, e); //mark the event as erred and move on. This will not be picked up by processing again persistentPortalEvent.setErrorAggregating(true); session.persist(persistentPortalEvent); } } return true; }
From source file:org.babyfish.test.hibernate.model.setandref.DbTest.java
License:Open Source License
private static void testMergeDepartment(final boolean loadBeforeMerge) { Object[] arr = load();/*from w w w .j av a 2 s. c o m*/ Action<Session> handler; final Department detachedDepartment1 = (Department) arr[0]; final Department detachedDepartment2 = (Department) arr[1]; final Employee detachedEmployee = (Employee) arr[2]; handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Department department1 = (Department) session.get(Department.class, 1L); Department department2 = (Department) session.get(Department.class, 2L); Employee employee = (Employee) session.get(Employee.class, 1L); detachedDepartment1.getEmployees().add(detachedEmployee); if (loadBeforeMerge) { assertCollection(department1.getEmployees()); assertCollection(department2.getEmployees()); assertReference(employee.getDepartment()); } session.merge(detachedDepartment1); assertCollection(department1.getEmployees(), employee); assertCollection(department2.getEmployees()); assertReference(employee.getDepartment(), department1); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Department department1 = (Department) session.get(Department.class, 1L); Department department2 = (Department) session.get(Department.class, 2L); Employee employee = (Employee) session.get(Employee.class, 1L); detachedDepartment2.getEmployees().add(detachedEmployee); if (loadBeforeMerge) { assertCollection(department1.getEmployees(), employee); assertCollection(department2.getEmployees()); assertReference(employee.getDepartment(), department1); } session.merge(detachedDepartment2); assertCollection(department1.getEmployees()); assertCollection(department2.getEmployees(), employee); assertReference(employee.getDepartment(), department2); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Department department1 = (Department) session.get(Department.class, 1L); Department department2 = (Department) session.get(Department.class, 2L); Employee employee = (Employee) session.get(Employee.class, 1L); detachedDepartment2.getEmployees().clear(); if (loadBeforeMerge) { assertCollection(department1.getEmployees()); assertCollection(department2.getEmployees(), employee); assertReference(employee.getDepartment(), department2); } session.merge(detachedDepartment2); assertCollection(department1.getEmployees()); assertCollection(department2.getEmployees()); assertReference(employee.getDepartment()); } }; execute(handler); }
From source file:org.babyfish.test.hibernate.model.setandset.DbTest.java
License:Open Source License
private void testMergeStudent(final boolean loadBeforeMerge) { Object[] arr = load();//from ww w. ja va 2 s .com final Student detachedStudent1 = (Student) arr[0]; final Student detachedStudent2 = (Student) arr[1]; final Course detachedCourse1 = (Course) arr[2]; final Course detachedCourse2 = (Course) arr[3]; Action<Session> handler; handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Student student1 = (Student) session.get(Student.class, 1L); Student student2 = (Student) session.get(Student.class, 2L); Course course1 = (Course) session.get(Course.class, 1L); Course course2 = (Course) session.get(Course.class, 2L); detachedStudent1.getCourses().add(detachedCourse1); if (loadBeforeMerge) { assertCollection(student1.getCourses()); assertCollection(student2.getCourses()); assertCollection(course1.getStudents()); assertCollection(course2.getStudents()); } session.merge(detachedStudent1); assertCollection(student1.getCourses(), course1); assertCollection(student2.getCourses()); assertCollection(course1.getStudents(), student1); assertCollection(course2.getStudents()); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Student student1 = (Student) session.get(Student.class, 1L); Student student2 = (Student) session.get(Student.class, 2L); Course course1 = (Course) session.get(Course.class, 1L); Course course2 = (Course) session.get(Course.class, 2L); detachedStudent1.getCourses().add(detachedCourse2); if (loadBeforeMerge) { assertCollection(student1.getCourses(), course1); assertCollection(student2.getCourses()); assertCollection(course1.getStudents(), student1); assertCollection(course2.getStudents()); } session.merge(detachedStudent1); assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses()); assertCollection(course1.getStudents(), student1); assertCollection(course2.getStudents(), student1); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Student student1 = (Student) session.get(Student.class, 1L); Student student2 = (Student) session.get(Student.class, 2L); Course course1 = (Course) session.get(Course.class, 1L); Course course2 = (Course) session.get(Course.class, 2L); detachedStudent2.getCourses().add(detachedCourse1); if (loadBeforeMerge) { assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses()); assertCollection(course1.getStudents(), student1); assertCollection(course2.getStudents(), student1); } session.merge(detachedStudent2); assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses(), course1); assertCollection(course1.getStudents(), student1, student2); assertCollection(course2.getStudents(), student1); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Student student1 = (Student) session.get(Student.class, 1L); Student student2 = (Student) session.get(Student.class, 2L); Course course1 = (Course) session.get(Course.class, 1L); Course course2 = (Course) session.get(Course.class, 2L); detachedStudent2.getCourses().add(detachedCourse2); if (loadBeforeMerge) { assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses(), course1); assertCollection(course1.getStudents(), student1, student2); assertCollection(course2.getStudents(), student1); } session.merge(detachedStudent2); assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses(), course1, course2); assertCollection(course1.getStudents(), student1, student2); assertCollection(course2.getStudents(), student1, student2); } }; execute(handler); handler = new Action<Session>() { @Override public void run(Session session) { session.setFlushMode(FlushMode.COMMIT); Student student1 = (Student) session.get(Student.class, 1L); Student student2 = (Student) session.get(Student.class, 2L); Course course1 = (Course) session.get(Course.class, 1L); Course course2 = (Course) session.get(Course.class, 2L); detachedStudent1.getCourses().remove(detachedCourse1); if (loadBeforeMerge) { assertCollection(student1.getCourses(), course1, course2); assertCollection(student2.getCourses(), course1, course2); assertCollection(course1.getStudents(), student1, student2); assertCollection(course2.getStudents(), student1, student2); } session.merge(detachedStudent1); assertCollection(student1.getCourses(), course2); assertCollection(student2.getCourses(), course1, course2); assertCollection(course1.getStudents(), student2); assertCollection(course2.getStudents(), student1, student2); } }; execute(handler); }
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."); }/* w w w. j ava 2 s . c om*/ 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();//from www. j av a 2s. c o m } catch (HibernateException ex) { throw convertHibernateAccessException(ex); } finally { session.setFlushMode(FlushMode.MANUAL); } } } }
From source file:org.bedework.calcore.hibernate.HibSessionImpl.java
License:Apache License
@Override public void createNoFlushQuery(final String s) throws CalFacadeException { if (exc != null) { // Didn't hear me last time? throw new CalFacadeException(exc); }// w w w .ja v a 2 s . c o m try { q = sess.createQuery(s); q.setFlushMode(FlushMode.COMMIT); } catch (Throwable t) { handleException(t); } }
From source file:org.bedework.carddav.server.dirHandlers.db.HibSessionImpl.java
License:Apache License
public void createNoFlushQuery(final String s) throws WebdavException { if (exc != null) { // Didn't hear me last time? throw new WebdavException(exc); }/*from w w w. jav a 2 s . co m*/ try { q = sess.createQuery(s); crit = null; q.setFlushMode(FlushMode.COMMIT); } catch (Throwable t) { handleException(t); } }
From source file:org.bedework.dumprestore.HibSession.java
License:Apache License
/** Set up for a hibernate interaction. Throw the object away on exception. * * @param sessFactory/*from w w w . j a v a2 s . c o m*/ * @param log * @throws CalFacadeException */ public HibSession(SessionFactory sessFactory, Logger log) throws CalFacadeException { try { this.log = log; sess = sessFactory.openSession(); sess.setFlushMode(FlushMode.COMMIT); // tx = sess.beginTransaction(); } catch (Throwable t) { exc = t; tx = null; // not even started. Should be null anyway close(); } }
From source file:org.bedework.dumprestore.restore.HibRestore.java
private synchronized void openHibSess() throws Throwable { openHibSess(FlushMode.COMMIT); }
From source file:org.bedework.util.hibernate.HibSessionImpl.java
License:Apache License
@Override public void createNoFlushQuery(final String s) throws HibException { if (exc != null) { // Didn't hear me last time? throw new HibException(exc); }/*from w w w .j a va2 s .com*/ try { q = sess.createQuery(s); crit = null; q.setFlushMode(FlushMode.COMMIT); } catch (Throwable t) { handleException(t); } }