Пример #1
0
 /**
  * @see
  *     org.kuali.rice.krad.dao.BusinessObjectDao#manageReadOnly(org.kuali.rice.krad.bo.PersistableBusinessObject)
  */
 public PersistableBusinessObject manageReadOnly(PersistableBusinessObject bo) {
   Session session = ((HibernateEntityManager) entityManager).getSession();
   FlushMode currentFlushMode = session.getFlushMode();
   session.setFlushMode(
       FlushMode.MANUAL); // make sure the merge doesn't flush what we're trying to make read only
   PersistableBusinessObject managedBO = entityManager.merge(bo);
   session.setReadOnly(managedBO, true);
   session.setFlushMode(currentFlushMode);
   return managedBO;
 }
 private <T> T doWithManualSession(AbstractEvent event, Closure<T> callable) {
   Session session = event.getSession();
   FlushMode current = session.getFlushMode();
   try {
     session.setFlushMode(FlushMode.MANUAL);
     return callable.call();
   } finally {
     session.setFlushMode(current);
   }
 }
Пример #3
0
  public List<PlannedNotification> getPlannedNotificationsForCorrespondence() {
    List<PlannedNotification> result;

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
      Query query =
          session
              .createQuery(
                  "from PlannedNotification p left join fetch p.userBasedRecipientInternal where p.eventName = :var")
              .setString(
                  "var",
                  NotificationEventTypeEnum.CORRESPONDENCE_CREATED_OR_UPDATED_EVENT.toString());

      result = query.list().subList(0, 1);
    } catch (DataAccessResourceFailureException e) {
      log.error(e.getMessage());
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (HibernateException e) {
      log.error(e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage());
    } finally {
      session.close();
    }
    return result;
  }
Пример #4
0
  @Test
  public void testFlushSQL() {
    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          entityManager.createNativeQuery("delete from Person").executeUpdate();
        });
    doInJPA(
        this::entityManagerFactory,
        entityManager -> {
          log.info("testFlushSQL");
          // tag::flushing-manual-flush-example[]
          Person person = new Person("John Doe");
          entityManager.persist(person);

          Session session = entityManager.unwrap(Session.class);
          session.setFlushMode(FlushMode.MANUAL);

          assertTrue(
              ((Number) entityManager.createQuery("select count(id) from Person").getSingleResult())
                      .intValue()
                  == 0);

          assertTrue(
              ((Number) session.createSQLQuery("select count(*) from Person").uniqueResult())
                      .intValue()
                  == 0);
          // end::flushing-manual-flush-example[]
        });
  }
Пример #5
0
 /** Retrieve the Spring-managed Session for the current thread, if any. */
 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");
   }
 }
Пример #6
0
  private Session openSession() throws HibernateException {
    if (localHibernateSession != null) throw new HibernateException("Re-entrant call not allowed.");

    localHibernateSession = sessionFactory.openSession();
    localHibernateSession.setFlushMode(FlushMode.MANUAL);
    return localHibernateSession;
  }
  @Test
  public void testFlushSQL() {
    doInJPA(
        entityManager -> {
          entityManager.createNativeQuery("delete from Post").executeUpdate();
        });
    doInJPA(
        entityManager -> {
          log.info("testFlushSQL");
          Post post = new Post("Hibernate");
          post.setId(1L);
          entityManager.persist(post);

          Session session = entityManager.unwrap(Session.class);
          session.setFlushMode(FlushMode.MANUAL);

          assertTrue(
              ((Number) entityManager.createQuery("select count(id) from Post").getSingleResult())
                      .intValue()
                  == 0);

          assertTrue(
              ((Number) session.createSQLQuery("select count(*) from Post").uniqueResult())
                      .intValue()
                  == 0);
        });
  }
Пример #8
0
  /**
   * Gets the planned notifications for the list of sites that are passed in. This method access the
   * db using a new session from the hibernate session factory.
   *
   * @param hcsList the hcs list
   * @return the planned notifications
   */
  public List<PlannedNotification> getPlannedNotificationsForUpdateMasterSubject() {
    List<PlannedNotification> result;

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
      Query query =
          session
              .createQuery("from PlannedNotification p where p.eventName = :var")
              .setString("var", NotificationEventTypeEnum.MASTER_SUBJECT_UPDATED_EVENT.toString());

      result = query.list();
    } catch (DataAccessResourceFailureException e) {
      log.error(e.getMessage());
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (HibernateException e) {
      log.error(e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage());
    } finally {
      session.close();
    }
    return result;
  }
Пример #9
0
 /**
  * Returns the thread attached session or open a new one if no exist before
  *
  * @return session
  */
 public static Session currentSession() {
   Session s = (Session) threadSession.get();
   if (s == null && (threadRollback.get() == null)) {
     s = sessionFactory.openSession();
     s.setFlushMode(FlushMode.AUTO);
     s.setCacheMode(CacheMode.NORMAL);
     threadSession.set(s);
   }
   return s;
 }
Пример #10
0
 /**
  * 获取当前线程绑定的session
  *
  * @return
  */
 public static Session currentSession() {
   Session session = (Session) threadLocal.get();
   // 如果该线程还没有Session,则创建一个新的Session
   if (session == null) {
     session = sessionFactory.openSession();
     session.setFlushMode(FlushMode.MANUAL);
     threadLocal.set(session);
   }
   return session;
 }
 /**
  * Open a Session for the SessionFactory that this filter uses.
  *
  * <p>The default implementation delegates to the <code>SessionFactory.openSession</code> method
  * and sets the <code>Session</code>'s flush mode to "MANUAL".
  *
  * @param sessionFactory the SessionFactory that this filter uses
  * @return the Session to use
  * @throws DataAccessResourceFailureException if the Session could not be created
  * @see org.hibernate.FlushMode#MANUAL
  */
 protected Session openSession(SessionFactory sessionFactory)
     throws DataAccessResourceFailureException {
   try {
     Session session = SessionFactoryUtils.openSession(sessionFactory);
     session.setFlushMode(FlushMode.MANUAL);
     return session;
   } catch (HibernateException ex) {
     throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
   }
 }
 /**
  * Sets the target object to read-only using the given SessionFactory instance. This avoids
  * Hibernate performing any dirty checking on the object
  *
  * @see #setObjectToReadWrite(Object, org.hibernate.SessionFactory)
  * @param target The target object
  * @param sessionFactory The SessionFactory instance
  */
 public static void setObjectToReadyOnly(Object target, SessionFactory sessionFactory) {
   Session session = sessionFactory.getCurrentSession();
   if (canModifyReadWriteState(session, target)) {
     if (target instanceof HibernateProxy) {
       target = ((HibernateProxy) target).getHibernateLazyInitializer().getImplementation();
     }
     session.setReadOnly(target, true);
     session.setFlushMode(FlushMode.MANUAL);
   }
 }
Пример #13
0
 /**
  * Inicializa una sesión de hibernate en base al editor indicado
  *
  * @param id que se asociará a la nueva sesión
  */
 public AbstractController(String editorId, GenericDAOImpl<X, Long> dao) {
   LOGGER = Logger.getLogger(getClass());
   session = HibernateUtil.getEditorSession(editorId);
   session.setFlushMode(FlushMode.MANUAL);
   // session.setFlushMode(FlushMode.NEVER);
   /*
   session = HibernateUtil.getSessionFactory().getCurrentSession();
   session.beginTransaction();
    */
   this.editorId = editorId;
   this.dao = dao;
   this.dao.setSession(session);
 }
  /**
   * Returns the ThreadLocal Session instance. Lazy initialize the <code>SessionFactory</code> if
   * needed.
   *
   * @return Session
   * @throws HibernateException
   */
  public static Session getSession() throws HibernateException {
    Session session = threadLocal.get();

    if (session == null || !session.isOpen()) {
      if (sessionFactory == null) {
        rebuildSessionFactory();
      }
      session = (sessionFactory != null) ? sessionFactory.openSession() : null;
      session.setFlushMode(FlushMode.ALWAYS);
      threadLocal.set(session);
    }
    session.clear();
    return session;
  }
 private boolean bindSession() {
   if (sessionFactory == null) {
     throw new IllegalStateException("No sessionFactory property provided");
   }
   final Object inStorage = TransactionSynchronizationManager.getResource(sessionFactory);
   if (inStorage != null) {
     ((SessionHolder) inStorage).getSession().flush();
     return false;
   } else {
     Session session = SessionFactoryUtils.getSession(sessionFactory, true);
     session.setFlushMode(FlushMode.AUTO);
     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
     return true;
   }
 }
Пример #16
0
  private Session openSession(boolean readOnly) {
    final Session session = sessionFactory.openSession();
    try {
      session.setDefaultReadOnly(readOnly);
      session.setFlushMode(FlushMode.AUTO);
      session.setCacheMode(CacheMode.NORMAL);
      ManagedSessionContext.bind(session);
      if (!readOnly) {
        session.beginTransaction();
      }
    } finally {

    }
    return session;
  }
 public Object intercept(Invocation invocation) throws Exception {
   try {
     Session session = sessionFactory.openSession();
     session.setFlushMode(FlushMode.MANUAL);
     SessionHolder sessionHolder = new SessionHolder(session);
     TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder);
     return invocation.invoke();
   } catch (Exception e) {
     throw e;
   } finally {
     SessionHolder sessionHolder =
         (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
     sessionHolder.getSession().close();
   }
 }
Пример #18
0
 public void doDelete(X registro) {
   try {
     dao.doDelete(registro);
   } catch (HibernateException he) {
     if (getSession().isOpen()) {
       HibernateUtil.rollback(getSession().getTransaction());
       HibernateUtil.closeEditorSession(getEditorId());
     }
     HibernateUtil.procesarError(he);
     session = HibernateUtil.getEditorSession(editorId);
     session.setFlushMode(FlushMode.MANUAL);
     dao.setSession(session);
     HibernateUtil.verSesiones();
   }
 }
 @Override
 public void run() {
   log.trace("started");
   Session session = sessionFactory.withOptions().tenantIdentifier(tenantId).openSession();
   session.setFlushMode(FlushMode.MANUAL);
   session.setCacheMode(cacheMode);
   session.setDefaultReadOnly(true);
   try {
     loadAllFromQueue(session);
   } catch (Exception exception) {
     errorHandler.handleException(log.massIndexerExceptionWhileTransformingIds(), exception);
   } finally {
     producerEndSignal.countDown();
     session.close();
   }
   log.trace("finished");
 }
Пример #20
0
  @Override
  @RawEventsTransactional
  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 =
          this.toPortalEvent(
              persistentPortalEvent.getEventData(), persistentPortalEvent.getEventType());
      final Boolean stopAggregation = handler.apply(portalEvent);
      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();
      }

      if (stopAggregation) {
        this.logger.debug("Aggregation stop requested after processing event {}", portalEvent);
        return true;
      }
    }

    return false;
  }
Пример #21
0
  /**
   * Gets the planned notifications for the list of sites that are passed in. This method access the
   * db using a new session from the hibernate session factory.
   *
   * @param hcsList the hcs list
   * @return the planned notifications
   */
  public List<PlannedNotification> getPlannedNotifications(List<HealthcareSite> hcsList) {
    List<PlannedNotification> result;
    List<String> nciCodeList = new ArrayList<String>();
    for (HealthcareSite hcs : hcsList) {
      if (hcs != null) {
        nciCodeList.add(hcs.getPrimaryIdentifier());
      }
    }

    SessionFactory sessionFactory = (SessionFactory) applicationContext.getBean("sessionFactory");
    Session session = sessionFactory.openSession(sessionFactory.getCurrentSession().connection());
    session.setFlushMode(FlushMode.MANUAL);
    result = new ArrayList<PlannedNotification>();
    try {
      Query query =
          session
              .createQuery(
                  "select p from PlannedNotification p, HealthcareSite o, Identifier i where p = any elements(o.plannedNotificationsInternal) and "
                      + "i = any elements(o.identifiersAssignedToOrganization) and i.primaryIndicator = 'true' and "
                      + "i.value in (:nciCodeList)")
              .setParameterList("nciCodeList", nciCodeList);

      result = query.list();
    } catch (DataAccessResourceFailureException e) {
      log.error(e.getMessage());
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (HibernateException e) {
      log.error(e.getMessage());
    } catch (Exception e) {
      log.error(e.getMessage());
    } finally {
      session.close();
    }
    return result;
  }
 protected Session getSession(SessionFactory sessionFactory)
     throws DataAccessResourceFailureException {
   Session session = super.getSession(sessionFactory);
   session.setFlushMode(FlushMode.AUTO);
   return session;
 }
Пример #23
0
 @Before
 public void initFlush() throws IOException {
   Session session = getSession(getEntityManager());
   session.setFlushMode(getFlushMode());
 }
  @Override
  protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    try {
      logger.debug("running offer update rules job:" + Calendar.getInstance().getTimeInMillis());

      // bind session to thread
      Session session = null;
      try {
        session = SessionFactoryUtils.getSession(sessionFactory, false);
      }
      // If not already bound the Create and Bind it!
      catch (java.lang.IllegalStateException ex) {
        session = SessionFactoryUtils.getSession(sessionFactory, true);
        TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
      }
      session.setFlushMode(FlushMode.AUTO);

      // find awards whose offers are expired only on bl failure
      // really should fire working memory rules against rater that has expired
      // awards

      List<Offer> expired = awardManagerService.findExpiredAwardOffers();

      logger.debug("number of expired offers:" + expired.size());

      /*for (AwardOffer awardOffer : expired) {
      	//logger.debug(awardOffer.getOffer().getExpireDateMillis());

      	//delete any expired offer
      	//remove the offer from the award
      	Award a = awardOffer.getAward();
      	a.getOffers().remove(awardOffer);
      	awardManagerService.saveAward(a);

      	awardManagerService.deleteAwardOffer(awardOffer);

      	if(awardOffer.getAward() != null)
      	{
      		//dont throw if one has a problem
      		try {
      			updateAwardOfferMessageProducer
      			.generateMessage(
      					awardOffer.getAward(),
      					awardOffer.getAwardType(),
      					awardOffer.getAward().getOwner());
      		} catch (JsonGenerationException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JsonMappingException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (JMSException e) {
      			logger.error("problem udating expired offer", e);
      		} catch (IOException e) {
      			logger.error("problem udating expired offer", e);
      		}
      	}


      }*/

    } catch (com.noi.utility.spring.service.BLServiceException e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } catch (Exception e) {
      logger.error("problem updating expired offers", e);
      throw new JobExecutionException(e);
    } finally {
      // unbind
      SessionHolder sessionHolder =
          (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
      if (!FlushMode.MANUAL.equals(sessionHolder.getSession().getFlushMode())) {
        sessionHolder.getSession().flush();
      }
      SessionFactoryUtils.closeSession(sessionHolder.getSession());
    }
  }
Пример #25
0
 public void setFlushMode(FlushMode flushMode) {
   session.setFlushMode(flushMode);
 }
Пример #26
0
 private void configureSession(Session session, UnitOfWork uow) {
   session.setDefaultReadOnly(uow.readOnly());
   session.setCacheMode(uow.cacheMode());
   session.setFlushMode(uow.flushMode());
 }