Example usage for org.hibernate Session saveOrUpdate

List of usage examples for org.hibernate Session saveOrUpdate

Introduction

In this page you can find the example usage for org.hibernate Session saveOrUpdate.

Prototype

void saveOrUpdate(Object object);

Source Link

Document

Either #save(Object) or #update(Object) the given instance, depending upon resolution of the unsaved-value checks (see the manual for discussion of unsaved-value checking).

Usage

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

private DefaultPathTasks updateDefaultPathTasks(int p_actionType, Date p_baseDate, List p_wfTaskInfos,
        Workflow p_wfClone, long p_completedTaskId, boolean p_isActiveTaskReassigned, Date p_originalBaseDate,
        Session p_session) throws Exception {
    int size = p_wfTaskInfos.size();
    Hashtable ht = p_wfClone.getTasks();
    FluxCalendar defaultCalendar = ServerProxy.getCalendarManager()
            .findDefaultCalendar(String.valueOf(p_wfClone.getCompanyId()));
    UserFluxCalendar userCalendar = null;

    DefaultPathTasks dpt = new DefaultPathTasks();
    Date estimatedDate = p_isActiveTaskReassigned ? p_baseDate : p_originalBaseDate;

    boolean found = p_completedTaskId <= 0;
    // loop thru the tasks following the given start task for updating
    // the estimated dates for the tasks and possibly workflow.
    boolean firstTime = true;
    boolean activeTaskAccepted = false;
    for (int i = 0; i < size; i++) {
        WfTaskInfo wfTaskInfo = (WfTaskInfo) p_wfTaskInfos.get(i);
        if (!found) {
            found = p_completedTaskId == wfTaskInfo.getId();
        } else {//from  w  ww .  j  a  v  a 2 s  . com
            TaskImpl task = (TaskImpl) ht.get(new Long(wfTaskInfo.getId()));

            if (task != null) {
                Date acceptBy = ServerProxy.getEventScheduler().determineDate(estimatedDate, defaultCalendar,
                        wfTaskInfo.getAcceptanceDuration());

                task.setEstimatedAcceptanceDate(acceptBy);

                long duration = wfTaskInfo.getTotalDuration();

                if (firstTime) {
                    firstTime = false;
                    if (activeTaskAccepted = (task.getAcceptor() != null
                            && task.getAcceptedDate().compareTo(p_originalBaseDate) >= 0)) {
                        removeReservedTime(task.getId(), task.getAcceptor());

                        userCalendar = ServerProxy.getCalendarManager()
                                .findUserCalendarByOwner(task.getAcceptor());

                        if (p_isActiveTaskReassigned) {
                            // reset acceptor and acceptance date
                            task.setAcceptor(null);
                            task.setAcceptedDate(null);
                            task.setState(TaskImpl.STATE_ACTIVE);
                        } else {
                            estimatedDate = task.getAcceptedDate();
                            duration = wfTaskInfo.getCompletionDuration();
                        }
                    }
                    // possibly create proposed type reserved times
                    createProposedReservedTimes(p_actionType, estimatedDate, wfTaskInfo, task,
                            ReservedTime.TYPE_PROPOSED, p_isActiveTaskReassigned, p_session);
                }

                Date completeBy = ServerProxy.getEventScheduler().determineDate(estimatedDate,
                        userCalendar == null ? (BaseFluxCalendar) defaultCalendar
                                : (BaseFluxCalendar) userCalendar,
                        duration);

                task.setEstimatedCompletionDate(completeBy);

                if (activeTaskAccepted && !p_isActiveTaskReassigned) {
                    addReservedTimeToUserCalendar(userCalendar,
                            buildReservedTimeName(wfTaskInfo.getName(), task), ReservedTime.TYPE_ACTIVITY,
                            task.getAcceptedDate(), completeBy, task.getIdAsLong(), p_session);
                }

                estimatedDate = completeBy;
                activeTaskAccepted = false; // reset it
                TaskInfo ti = new TaskInfo(task.getId(), task.getTaskName(), task.getState(), acceptBy,
                        completeBy, null, null, task.getType());

                if (wfTaskInfo.getOverdueToPM() != 0) {
                    ti.setOverdueToPM(wfTaskInfo.getOverdueToPM());
                }

                if (wfTaskInfo.getOverdueToUser() != 0) {
                    ti.setOverdueToUser(wfTaskInfo.getOverdueToUser());
                }

                dpt.addTaskInfo(ti);
                p_session.saveOrUpdate(task);
            }
        }

        // There's an edge case where all nodes could go thru on common
        // decision node. Therefore, let's start from the START node...
        if (i == (size - 1) && dpt.size() == 0 && !wfTaskInfo.followedByExitNode()) {
            i = -1;
            found = true;
        }
    }

    // For sla report issue.
    // No need to set estimated completion date for a workflow if
    // the advanced task happens to be the last one.
    // User can override the estimatedCompletionDate.
    if ((!estimatedDate.equals(p_baseDate)) && (!p_wfClone.isEstimatedCompletionDateOverrided())) {
        p_wfClone.setEstimatedCompletionDate(estimatedDate);
        sendNotification(p_wfClone);
    }

    // For sla report issue.
    p_wfClone.updateTranslationCompletedDates();

    return dpt;
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

private void addReservedTimeToUserCalendar(UserFluxCalendar p_userCalendar, String p_name, String p_type,
        Date p_startDate, Date p_completeBy, Long p_taskId, Session p_session) throws Exception {
    // if calendaring module is not installed, don't create reserved times.
    if (!Modules.isCalendaringInstalled()) {
        return;//from w  w  w.j a  v a 2  s.  c  om
    }

    // create new reserved time for user
    TimeZone tz = p_userCalendar.getTimeZone();
    Timestamp start = new Timestamp(tz);
    start.setDate(p_startDate);
    Timestamp end = new Timestamp(tz);
    end.setDate(p_completeBy);

    ReservedTime rt = new ReservedTime(p_name, p_type, start, start.getHour(), start.getMinute(), end,
            end.getHour(), end.getMinute(), null, p_taskId);

    // cloneCalendar.addReservedTime(rtClone);
    p_userCalendar.addReservedTime(rt);
    p_session.save(rt);

    // now add the buffer (if not set to zero)
    if (ReservedTime.TYPE_ACTIVITY.equals(p_type) && p_userCalendar.getActivityBuffer() > 0) {
        Timestamp bufferEnd = new Timestamp(tz);
        bufferEnd.setDate(end.getDate());
        bufferEnd.add(Timestamp.HOUR, p_userCalendar.getActivityBuffer());
        ReservedTime buffer = new ReservedTime(p_name, ReservedTime.TYPE_BUFFER, end, end.getHour(),
                end.getMinute(), bufferEnd, bufferEnd.getHour(), bufferEnd.getMinute(), null, p_taskId);
        p_userCalendar.addReservedTime(buffer);
        p_session.save(buffer);
    }
    p_session.saveOrUpdate(p_userCalendar);
}

From source file:com.globalsight.everest.workflowmanager.WorkflowManagerLocal.java

License:Apache License

/**
 * Change workflow priority.//from  w  ww . j a va2 s . c  o  m
 * 
 */
public void updatePriority(long p_workflowId, int p_priority) throws WorkflowManagerException, RemoteException {
    Session session = HibernateUtil.getSession();
    Transaction tx = session.beginTransaction();

    try {
        Workflow wf = (Workflow) session.get(WorkflowImpl.class, new Long(p_workflowId));
        wf.setPriority(p_priority);
        session.saveOrUpdate(wf);
        tx.commit();
    } catch (Exception e) {
        String[] args = { String.valueOf(p_workflowId) };
        throw new WorkflowManagerException(WorkflowManagerException.MSG_FAILED_TO_UPDATE_PCD, args, e);
    }
}

From source file:com.globalsight.persistence.hibernate.HibernateUtil.java

License:Apache License

/**
 * Save or update some instance. More informations you can see
 * <code>saveOrUpdate(Object object)</code>.
 * /*from   w  w w  . j av  a 2  s . co  m*/
 * @param objects
 *            persistent classes
 * @throws Exception
 */
public static void saveOrUpdate(Collection<?> objects) throws Exception {
    if (objects != null && objects.size() > 0) {
        Session session = getSession();
        Transaction tx = getTransaction();
        try {
            Iterator<?> iterator = objects.iterator();
            int n = 0;
            while (iterator.hasNext()) {
                session.saveOrUpdate(iterator.next());

                // Release memory.
                n++;
                if (n % 20 == 0) {
                    session.flush();
                    session.clear();
                }
            }

            commit(tx);
        } catch (Exception e) {
            rollback(tx);
            e.printStackTrace();
            throw e;
        }
    }
}

From source file:com.globalsight.persistence.hibernate.HibernateUtil.java

License:Apache License

/**
 * Either <tt>save()</tt> or <tt>update()</tt> the given instance, depending
 * upon the value of its identifier property. By default the instance is
 * always saved. This behaviour may be adjusted by specifying an
 * <tt>unsaved-value</tt> attribute of the identifier property mapping. This
 * operation cascades to associated instances if the association is mapped
 * with <tt>cascade="save-update"</tt>.
 * /*from w w w .j  a v a  2s.  c om*/
 * @see Session#save(java.lang.Object)
 * @see Session#update(Object object)
 * @param object
 *            a transient or detached instance containing new or updated
 *            state
 * @throws Exception
 */
public static void saveOrUpdate(Object object) throws HibernateException {
    if (object == null) {
        return;
    }
    Session session = getSession();
    Transaction tx = getTransaction();

    try {
        session.saveOrUpdate(object);
        commit(tx);
    } catch (HibernateException e) {
        rollback(tx);
        throw e;
    }
}

From source file:com.globalsight.persistence.hibernate.HibernateUtil.java

License:Apache License

/**
 * /*  ww  w .ja v  a 2 s. co  m*/
 * 
 * @param session
 *            the session is not null, managed by invoked method.
 * @param objects
 *            need updated data
 * @throws Exception
 */
public static void saveOrUpdate(Session session, Collection<?> objects) throws Exception {
    if (objects != null && objects.size() > 0) {

        if (session == null) {
            throw new Exception("No Hibernate session provided, can not access database.");
        }
        Iterator<?> iterator = objects.iterator();
        int n = 0;
        while (iterator.hasNext()) {
            session.saveOrUpdate(iterator.next());
            // Release memory.
            n++;
            if (n % 20 == 0) {
                session.flush();
                session.clear();
            }
        }
    }
}

From source file:com.gmvc.server.impl.CRUDImpl.java

License:LGPL

/**
 * Kayit isleme islemi (insert ve update)
 * /*from ww  w  .j  a v  a  2s  .  c o  m*/
 * @param clientModel
 * 
 * @return RetVal sonuc nesnesi
 */
public RetVal save(C clientModel, List<EffectedDetail> effectedDetailList) {
    RetVal result = new RetVal();

    Session session = DBUtils.getSession();
    try {
        session.beginTransaction();

        S model = DBUtils.getMapper().map(clientModel, serverClass);

        RetVal before = beforeSave(session, model, effectedDetailList);
        if (before != null) {
            session.getTransaction().rollback();
            return before;
        }

        session.saveOrUpdate(model);

        RetVal after = afterSave(session, model, effectedDetailList);
        if (after != null) {
            session.getTransaction().rollback();
            return after;
        }
        clearJunkDetailModels(session, effectedDetailList);

        session.getTransaction().commit();
        result.setEffectedRows(1);

    } catch (Exception e) {
        session.getTransaction().rollback();

        if (e.getCause() != null && e.getCause().getMessage() != null)
            result.setMessage(e.getCause().getMessage());
        else
            result.setMessage(e.getMessage());
        result.setEffectedRows(0);
    }

    return result;
}

From source file:com.google.api.ads.adwords.awreporting.model.persistence.sql.SqlAuthTokenPersister.java

License:Open Source License

@Override
@Transactional//from  www  . j  ava2 s.  com
public void persistAuthToken(AuthToken authToken) {
    Session session = this.sessionFactory.getCurrentSession();
    session.saveOrUpdate(authToken);
}

From source file:com.google.api.ads.adwords.awreporting.model.persistence.sql.SqlReportEntitiesPersister.java

License:Open Source License

/**
 * Persists all the given entities into the DB configured in the {@code SessionFactory}.
 *//* ww w  .j a v  a2 s. c o m*/
@Override
@Transactional
public void persistReportEntities(List<? extends Report> reportEntities) {
    int batchFlush = 0;
    Session session = sessionFactory.getCurrentSession();

    for (Report report : reportEntities) {
        report.setRowId();
        session.saveOrUpdate(report);
        batchFlush++;

        if (batchFlush == batchSize) {
            session.flush();
            session.clear();
            batchFlush = 0;
        }
    }

    if (batchFlush > 0) {
        session.flush();
        session.clear();
    }
}

From source file:com.google.api.ads.adwords.awreporting.model.persistence.sql.SqlReportEntitiesPersister.java

License:Open Source License

@Override
@Transactional
public <T> T save(T t) {
    Session session = sessionFactory.getCurrentSession();
    session.saveOrUpdate(t);
    return t;
}