Example usage for javax.persistence EntityManager flush

List of usage examples for javax.persistence EntityManager flush

Introduction

In this page you can find the example usage for javax.persistence EntityManager flush.

Prototype

public void flush();

Source Link

Document

Synchronize the persistence context to the underlying database.

Usage

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.UserSessionUrlDaoImpl.java

@Override
@Transactional/*from   w w  w. j  a  v a 2  s .  c o m*/
public void deleteOldSessionUrls(Session session, ConferenceUser user) {
    final EntityManager entityManager = this.getEntityManager();

    //fetch session
    SessionImpl sessionFromDb = sessionDao.getSession(session.getSessionId());
    //fetch user
    ConferenceUserImpl userFromDb = blackboardUserDao.getUser(user.getUserId());
    //assert they are valid
    Validate.notNull(sessionFromDb);
    Validate.notNull(userFromDb);

    final NaturalIdQuery<UserSessionUrlImpl> query = this.createNaturalIdQuery(UserSessionUrlImpl.class);
    query.using(UserSessionUrlImpl_.session, sessionFromDb);
    query.using(UserSessionUrlImpl_.user, userFromDb);

    UserSessionUrlImpl url = query.load();

    entityManager.remove(url);
    entityManager.flush();
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllProducts() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from  w w  w  .  j  a  v a  2 s  .  c om*/

    Query q = entityManager.createQuery("DELETE FROM Product ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllCategories() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w w  w  .  j a va2  s . co  m

    Query q = entityManager.createQuery("DELETE FROM Category");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void deleteAllUsers() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//ww w .j ava  2s .c  om

    Query q = entityManager.createQuery("DELETE FROM FStoreUser ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

From source file:name.livitski.tools.persista.TransactionalWork.java

/**
 * Performs the {@link #code database operations} provided by
 * the subclass in JPA transactional brackets. If there is currently
 * no active transaction at the entity manager, a new transaction
 * is started./*from w  ww.  j  a va 2 s. c  om*/
 * If the code finishes normally and does not request the rollback,
 * the transaction is committed if it was started by this method
 * (local transaction).
 * If the implementor's code throws an exception or requests the
 * rollback, the local transaction is rolled back and any ongoing
 * transaction is marked
 * {@link EntityTransaction#setRollbackOnly() rollback-only}.
 * @param db the entity manager the operation will be performed with
 * @return <code>true</code> if the transaction has or may still
 * be committed
 * @throws AbstractStorageException indicates an error during
 * the operation
 * @throws RuntimeException any unchecked implementor's exceptions
 * will be rethrown
 * @see EntityManager#getTransaction()
 */
public boolean exec(final EntityManager db) throws AbstractStorageException {
    final EntityTransaction transaction = db.getTransaction();
    boolean commit = false;
    Exception status = null;
    boolean localTransaction;
    if (transaction.isActive())
        localTransaction = false;
    else {
        transaction.begin();
        localTransaction = true;
    }
    try {
        commit = code(db);
        return commit;
    } catch (AbstractStorageException fault) {
        status = fault;
        throw fault;
    } catch (RuntimeException fault) {
        status = fault;
        throw fault;
    } finally {
        if (!localTransaction) {
            if (commit)
                db.flush();
            else
                transaction.setRollbackOnly();
        } else if (!commit || transaction.getRollbackOnly()) {
            try {
                transaction.rollback();
            } catch (RuntimeException fault) {
                if (null != status)
                    log().error("Transaction rollback failed", fault);
                else
                    throw fault;
            }
        } else // commit local transaction
        {
            try {
                transaction.commit();
            } catch (RuntimeException fault) {
                throw fault;
            }
        }
    }
}

From source file:org.jasig.portal.events.aggr.PortalRawEventsAggregatorImpl.java

private EventProcessingResult doAggregateRawEventsInternal() {
    if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME
                + " must be owned by the current thread and server");
    }//  w  w w .j  ava2s  .c o  m

    if (!this.portalEventDimensionPopulator.isCheckedDimensions()) {
        //First time aggregation has happened, run populateDimensions to ensure enough dimension data exists
        final boolean populatedDimensions = this.portalEventAggregationManager.populateDimensions();
        if (!populatedDimensions) {
            this.logger.warn(
                    "Aborting raw event aggregation, populateDimensions returned false so the state of date/time dimensions is unknown");
            return null;
        }
    }

    //Flush any dimension creation before aggregation
    final EntityManager entityManager = this.getEntityManager();
    entityManager.flush();
    entityManager.setFlushMode(FlushModeType.COMMIT);

    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(ProcessingType.AGGREGATION, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    final String previousServerName = eventAggregatorStatus.getServerName();
    if (previousServerName != null && !serverName.equals(previousServerName)) {
        this.logger.debug("Last aggregation run on {} clearing all aggregation caches", previousServerName);
        final Session session = getEntityManager().unwrap(Session.class);
        final Cache cache = session.getSessionFactory().getCache();
        cache.evictEntityRegions();
    }

    eventAggregatorStatus.setServerName(serverName);

    //Calculate date range for aggregation
    DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    if (lastAggregated == null) {
        lastAggregated = portalEventDao.getOldestPortalEventTimestamp();

        //No portal events to aggregate, skip aggregation
        if (lastAggregated == null) {
            return new EventProcessingResult(0, null, null, true);
        }

        //First time aggregation has run, initialize the CLEAN_UNCLOSED status to save catch-up time 
        final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao
                .getEventAggregatorStatus(ProcessingType.CLEAN_UNCLOSED, true);
        AggregationIntervalInfo oldestMinuteInterval = this.intervalHelper
                .getIntervalInfo(AggregationInterval.MINUTE, lastAggregated);
        cleanUnclosedStatus.setLastEventDate(oldestMinuteInterval.getStart().minusMinutes(1));
        eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);
    }

    final DateTime newestEventTime = DateTime.now().minus(this.aggregationDelay).secondOfMinute()
            .roundFloorCopy();

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    final MutableInt events = new MutableInt();
    final MutableObject lastEventDate = new MutableObject(newestEventTime);

    boolean complete;
    try {
        currentThread.setName(currentName + "-" + lastAggregated + "_" + newestEventTime);

        logger.debug("Starting aggregation of events between {} (inc) and {} (exc)", lastAggregated,
                newestEventTime);

        //Do aggregation, capturing the start and end dates
        eventAggregatorStatus.setLastStart(DateTime.now());

        complete = portalEventDao.aggregatePortalEvents(lastAggregated, newestEventTime,
                this.eventAggregationBatchSize,
                new AggregateEventsHandler(events, lastEventDate, eventAggregatorStatus));

        eventAggregatorStatus.setLastEventDate((DateTime) lastEventDate.getValue());
        eventAggregatorStatus.setLastEnd(DateTime.now());
    } finally {
        currentThread.setName(currentName);
    }

    //Store the results of the aggregation
    eventAggregationManagementDao.updateEventAggregatorStatus(eventAggregatorStatus);

    complete = complete
            && (this.eventAggregationBatchSize <= 0 || events.intValue() < this.eventAggregationBatchSize);
    return new EventProcessingResult(events.intValue(), lastAggregated,
            eventAggregatorStatus.getLastEventDate(), complete);
}

From source file:BO.UserHandler.java

public boolean updateDeviceToken(VUser u) {
    EntityManager em;
    EntityManagerFactory emf;/* w w  w .j  a  v a  2s. c  o m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();
    System.out.println("Updating token: " + u.getDeviceToken());
    try {
        em.getTransaction().begin();
        User user;
        user = (User) em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email")
                .setParameter("email", u.getEmail()).setMaxResults(1).getSingleResult();
        user.setDeviceToken(u.getDeviceToken());
        em.persist(user);
        em.flush();
        em.getTransaction().commit();

        return true;
    } catch (NoResultException e) {
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }

}

From source file:nl.b3p.kaartenbalie.struts.UserAction.java

@Override
public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    User user = getUser(dynaForm, request, true);
    ActionForward af = saveCheck(user, mapping, dynaForm, request);
    if (af != null) {
        return af;
        /*/*w  w w.  j a  va2 s . c om*/
         * Check if this user gets a valid capability when using this personalURL
         */
    }

    Organization org = user.getMainOrganization();
    if (org != null && !org.getHasValidGetCapabilities()) {
        // TODO: we should check for the combination of all organisations
        addAlternateMessage(mapping, request, CAPABILITY_WARNING_KEY);
    }

    /* controleren of er rollen zijn gekozen */
    Integer[] roleSelected = (Integer[]) dynaForm.get("roleSelected");
    int size = roleSelected.length;

    if (size < 1) {
        addAlternateMessage(mapping, request, NOROLES_WARNING_KEY);
    }

    populateUserObject(user, dynaForm, request);

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    if (user.getId() == null) {
        em.persist(user);
    } else {
        em.merge(user);
    }
    em.flush();

    updatePrincipal(request, user);

    populateUserForm(user, dynaForm, request);
    createLists(dynaForm, request);

    prepareMethod(dynaForm, request, EDIT, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:BO.UserHandler.java

public boolean login(VUser u) {

    EntityManager em;
    EntityManagerFactory emf;/*from  w w  w .j ava  2  s .c o  m*/
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {

        Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email");
        q.setParameter("email", u.getEmail());
        q.setMaxResults(1);
        q.getSingleResult();
        return true;
    } catch (NoResultException e) {
        em.getTransaction().begin();
        User userToInsert = new User(u.getEmail());
        em.persist(userToInsert);
        em.flush();
        em.getTransaction().commit();
        return true;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

private EventProcessingResult doAggregateRawEventsInternal() {
    if (!this.clusterLockService.isLockOwner(AGGREGATION_LOCK_NAME)) {
        throw new IllegalStateException("The cluster lock " + AGGREGATION_LOCK_NAME
                + " must be owned by the current thread and server");
    }/* w w w.java2 s. c om*/

    if (!this.portalEventDimensionPopulator.isCheckedDimensions()) {
        //First time aggregation has happened, run populateDimensions to ensure enough dimension data exists
        final boolean populatedDimensions = this.portalEventAggregationManager.populateDimensions();
        if (!populatedDimensions) {
            this.logger.warn(
                    "Aborting raw event aggregation, populateDimensions returned false so the state of date/time dimensions is unknown");
            return null;
        }
    }

    //Flush any dimension creation before aggregation
    final EntityManager entityManager = this.getEntityManager();
    entityManager.flush();
    entityManager.setFlushMode(FlushModeType.COMMIT);

    final IEventAggregatorStatus eventAggregatorStatus = eventAggregationManagementDao
            .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.AGGREGATION, true);

    //Update status with current server name
    final String serverName = this.portalInfoProvider.getUniqueServerName();
    final String previousServerName = eventAggregatorStatus.getServerName();
    if (previousServerName != null && !serverName.equals(previousServerName)) {
        this.logger.debug("Last aggregation run on {} clearing all aggregation caches", previousServerName);
        final Session session = getEntityManager().unwrap(Session.class);
        final Cache cache = session.getSessionFactory().getCache();
        cache.evictEntityRegions();
    }

    eventAggregatorStatus.setServerName(serverName);

    //Calculate date range for aggregation
    DateTime lastAggregated = eventAggregatorStatus.getLastEventDate();
    if (lastAggregated == null) {
        lastAggregated = portalEventDao.getOldestPortalEventTimestamp();

        //No portal events to aggregate, skip aggregation
        if (lastAggregated == null) {
            return new EventProcessingResult(0, null, null, true);
        }

        //First time aggregation has run, initialize the CLEAN_UNCLOSED status to save catch-up time 
        final IEventAggregatorStatus cleanUnclosedStatus = eventAggregationManagementDao
                .getEventAggregatorStatus(IEventAggregatorStatus.ProcessingType.CLEAN_UNCLOSED, true);
        AggregationIntervalInfo oldestMinuteInterval = this.intervalHelper
                .getIntervalInfo(AggregationInterval.MINUTE, lastAggregated);
        cleanUnclosedStatus.setLastEventDate(oldestMinuteInterval.getStart().minusMinutes(1));
        eventAggregationManagementDao.updateEventAggregatorStatus(cleanUnclosedStatus);
    }

    final DateTime newestEventTime = DateTime.now().minus(this.aggregationDelay).secondOfMinute()
            .roundFloorCopy();

    final Thread currentThread = Thread.currentThread();
    final String currentName = currentThread.getName();
    final MutableInt events = new MutableInt();
    final MutableObject lastEventDate = new MutableObject(newestEventTime);

    boolean complete;
    try {
        currentThread.setName(currentName + "-" + lastAggregated + "_" + newestEventTime);

        logger.debug("Starting aggregation of events between {} (inc) and {} (exc)", lastAggregated,
                newestEventTime);

        //Do aggregation, capturing the start and end dates
        eventAggregatorStatus.setLastStart(DateTime.now());

        complete = portalEventDao.aggregatePortalEvents(lastAggregated, newestEventTime,
                this.eventAggregationBatchSize,
                new AggregateEventsHandler(events, lastEventDate, eventAggregatorStatus));

        eventAggregatorStatus.setLastEventDate((DateTime) lastEventDate.getValue());
        eventAggregatorStatus.setLastEnd(DateTime.now());
    } finally {
        currentThread.setName(currentName);
    }

    //Store the results of the aggregation
    eventAggregationManagementDao.updateEventAggregatorStatus(eventAggregatorStatus);

    complete = complete
            && (this.eventAggregationBatchSize <= 0 || events.intValue() < this.eventAggregationBatchSize);
    return new EventProcessingResult(events.intValue(), lastAggregated,
            eventAggregatorStatus.getLastEventDate(), complete);
}