Example usage for org.hibernate Session evict

List of usage examples for org.hibernate Session evict

Introduction

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

Prototype

void evict(Object object);

Source Link

Document

Remove this instance from the session cache.

Usage

From source file:org.sakaiproject.gradebook.gwt.sakai.hibernate.GradebookToolServiceImpl.java

License:Educational Community License

public void updateCourseGradeRecords(final CourseGrade courseGrade,
        final Collection<CourseGradeRecord> gradeRecordsFromCall) throws StaleObjectModificationException {

    if (gradeRecordsFromCall.size() == 0) {
        log.debug("updateCourseGradeRecords called with zero grade records to update");
        return;/*from  ww w .  j  a va 2s .  com*/
    }

    if (logData.isDebugEnabled())
        logData.debug("BEGIN: Update " + gradeRecordsFromCall.size() + " course grades for gradebook="
                + courseGrade.getGradebook().getUid());

    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            for (Iterator iter = gradeRecordsFromCall.iterator(); iter.hasNext();) {
                session.evict(iter.next());
            }

            Date now = new Date();
            String graderId = authn.getUserUid();
            int numberOfUpdatedGrades = 0;

            for (Iterator iter = gradeRecordsFromCall.iterator(); iter.hasNext();) {
                // The modified course grade record
                CourseGradeRecord gradeRecordFromCall = (CourseGradeRecord) iter.next();
                gradeRecordFromCall.setGraderId(graderId);
                gradeRecordFromCall.setDateRecorded(now);
                try {
                    session.saveOrUpdate(gradeRecordFromCall);
                    session.flush();
                } catch (StaleObjectStateException sose) {
                    if (log.isInfoEnabled())
                        log.info(
                                "An optimistic locking failure occurred while attempting to update course grade records");
                    throw new StaleObjectModificationException(sose);
                }

                // Log the grading event
                session.save(new GradingEvent(courseGrade, graderId, gradeRecordFromCall.getStudentId(),
                        gradeRecordFromCall.getEnteredGrade()));

                numberOfUpdatedGrades++;
            }
            if (logData.isDebugEnabled())
                logData.debug("Changed " + numberOfUpdatedGrades + " course grades for gradebook="
                        + courseGrade.getGradebook().getUid());
            return null;
        }
    };
    try {
        getHibernateTemplate().execute(hc);
        if (logData.isDebugEnabled())
            logData.debug("END: Update " + gradeRecordsFromCall.size() + " course grades for gradebook="
                    + courseGrade.getGradebook().getUid());
    } catch (DataIntegrityViolationException e) {
        // It's possible that a previously ungraded student
        // was graded behind the current user's back before
        // the user saved the new grade. This translates
        // that case into an optimistic locking failure.
        if (log.isInfoEnabled())
            log.info("An optimistic locking failure occurred while attempting to update course grade records");
        throw new StaleObjectModificationException(e);
    }
}

From source file:org.sakaiproject.gradebook.gwt.sakai.hibernate.GradebookToolServiceImpl.java

License:Educational Community License

public void updateGradebook(final Gradebook gradebook) throws StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            // Get the gradebook and selected mapping from persistence
            Gradebook gradebookFromPersistence = (Gradebook) session.load(gradebook.getClass(),
                    gradebook.getId());/*from   ww w  .  ja va  2s.c  om*/
            GradeMapping mappingFromPersistence = gradebookFromPersistence.getSelectedGradeMapping();

            // If the mapping has changed, and there are explicitly entered
            // course grade records, disallow this update.
            if (!mappingFromPersistence.getId().equals(gradebook.getSelectedGradeMapping().getId())) {
                if (isExplicitlyEnteredCourseGradeRecords(gradebook.getId())) {
                    throw new IllegalStateException(
                            "Selected grade mapping cannot be changed, since explicit course grades exist.");
                }
            }

            // Evict the persisted objects from the session and update the gradebook
            // so the new grade mapping is used in the sort column update
            //session.evict(mappingFromPersistence);
            for (Iterator iter = gradebookFromPersistence.getGradeMappings().iterator(); iter.hasNext();) {
                session.evict(iter.next());
            }
            session.evict(gradebookFromPersistence);
            try {
                session.update(gradebook);
                session.flush();
            } catch (StaleObjectStateException e) {
                throw new StaleObjectModificationException(e);
            }

            return null;
        }
    };
    getHibernateTemplate().execute(hc);
}

From source file:org.sakaiproject.tool.gradebook.business.impl.GradebookManagerHibernateImpl.java

License:Educational Community License

/**
  *//*  www .j  a  va2  s  .  c  om*/
public void updateCourseGradeRecords(final CourseGrade courseGrade, final Collection gradeRecordsFromCall)
        throws StaleObjectModificationException {

    if (gradeRecordsFromCall.size() == 0) {
        log.debug("updateCourseGradeRecords called with zero grade records to update");
        return;
    }

    if (logData.isDebugEnabled())
        logData.debug("BEGIN: Update " + gradeRecordsFromCall.size() + " course grades for gradebook="
                + courseGrade.getGradebook().getUid());

    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            for (Iterator iter = gradeRecordsFromCall.iterator(); iter.hasNext();) {
                session.evict(iter.next());
            }

            Date now = new Date();
            String graderId = authn.getUserUid();
            int numberOfUpdatedGrades = 0;

            for (Iterator iter = gradeRecordsFromCall.iterator(); iter.hasNext();) {
                // The modified course grade record
                CourseGradeRecord gradeRecordFromCall = (CourseGradeRecord) iter.next();
                gradeRecordFromCall.setGraderId(graderId);
                gradeRecordFromCall.setDateRecorded(now);
                try {
                    session.saveOrUpdate(gradeRecordFromCall);
                    session.flush();
                } catch (StaleObjectStateException sose) {
                    if (log.isInfoEnabled())
                        log.info(
                                "An optimistic locking failure occurred while attempting to update course grade records");
                    throw new StaleObjectModificationException(sose);
                }

                // Log the grading event
                session.save(new GradingEvent(courseGrade, graderId, gradeRecordFromCall.getStudentId(),
                        gradeRecordFromCall.getEnteredGrade()));

                numberOfUpdatedGrades++;
            }
            if (logData.isDebugEnabled())
                logData.debug("Changed " + numberOfUpdatedGrades + " course grades for gradebook="
                        + courseGrade.getGradebook().getUid());
            return null;
        }
    };
    try {
        getHibernateTemplate().execute(hc);
        if (logData.isDebugEnabled())
            logData.debug("END: Update " + gradeRecordsFromCall.size() + " course grades for gradebook="
                    + courseGrade.getGradebook().getUid());
    } catch (DataIntegrityViolationException e) {
        // It's possible that a previously ungraded student
        // was graded behind the current user's back before
        // the user saved the new grade. This translates
        // that case into an optimistic locking failure.
        if (log.isInfoEnabled())
            log.info("An optimistic locking failure occurred while attempting to update course grade records");
        throw new StaleObjectModificationException(e);
    }
}

From source file:org.sakaiproject.tool.gradebook.business.impl.GradebookManagerHibernateImpl.java

License:Educational Community License

/**
 * update category and assignments in same session
 * for drop scores functionality//from  www  .j  a  v a  2  s . c  o  m
 */
public void updateCategoryAndAssignmentsPointsPossible(final Long gradebookId, final Category category)
        throws ConflictingAssignmentNameException, StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            updateCategory(category, session);

            // get assignments for this category
            Iterator iter = session.createQuery(
                    "select asn from Assignment asn where asn.gradebook.id=:gbid and asn.category=:category and asn.removed = false")
                    .setParameter("gbid", gradebookId).setParameter("category", category).list().iterator();
            while (iter.hasNext()) {
                Assignment assignment = (Assignment) iter.next();
                session.evict(assignment);
                if (assignment.getGradebook().getGrade_type() == GradebookService.GRADE_TYPE_LETTER) {
                    assignment.setUngraded(true);
                }
                if (assignment.getUngraded())
                    assignment.setNotCounted(true);
                // for drop score categories pointsPossible comes from the category
                assignment.setPointsPossible(category.getItemValue());
                updateAssignment(assignment, session);
            }
            return null;
        }
    };
    try {
        /** synchronize from external application*/

        Map oldTitles = new HashMap();
        List assignments = category.getAssignmentList();
        if (synchronizer != null) {
            for (Iterator iter = assignments.iterator(); iter.hasNext();) {
                Assignment assignment = (Assignment) iter.next();
                Assignment assign = getAssignment(assignment.getId());
                oldTitles.put(assignment.getId(), assign.getName());
            }
        }
        getHibernateTemplate().execute(hc);

        /** synchronize from external application*/
        for (Iterator iter = assignments.iterator(); iter.hasNext();) {
            Assignment assignment = (Assignment) iter.next();
            String oldTitle = (String) oldTitles.get(assignment.getId());
            assignment.setPointsPossible(category.getItemValue());
            if (synchronizer != null && oldTitle != null && !synchronizer.isProjectSite()
                    && !assignment.getUngraded()) {
                synchronizer.updateAssignment(oldTitle, assignment.getName(),
                        assignment.getGradebook().getGrade_type());
            }
        }
    } catch (HibernateOptimisticLockingFailureException holfe) {
        if (log.isInfoEnabled())
            log.info("An optimistic locking failure occurred while attempting to update an assignment");
        throw new StaleObjectModificationException(holfe);
    }
}

From source file:org.sakaiproject.tool.gradebook.business.impl.GradebookManagerHibernateImpl.java

License:Educational Community License

/**
 *
 * @param spreadsheet/*from   w w  w .j  av a  2 s .  c om*/
 */
public void updateSpreadsheet(final Spreadsheet spreadsheet)
        throws ConflictingAssignmentNameException, StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            // Ensure that we don't have the assignment in the session, since
            // we need to compare the existing one in the db to our edited assignment
            session.evict(spreadsheet);

            Spreadsheet sptFromDb = (Spreadsheet) session.load(Spreadsheet.class, spreadsheet.getId());
            List conflictList = ((List) session.createQuery(
                    "select spt from Spreadsheet as spt where spt.name = ? and spt.gradebook = ? and spt.id != ?")
                    .setString(0, spreadsheet.getName()).setEntity(1, spreadsheet.getGradebook())
                    .setLong(2, spreadsheet.getId().longValue()).list());
            int numNameConflicts = conflictList.size();
            if (numNameConflicts > 0) {
                throw new ConflictingAssignmentNameException(
                        "You can not save multiple spreadsheets in a gradebook with the same name");
            }

            session.evict(sptFromDb);
            session.update(spreadsheet);

            return null;
        }
    };
    try {
        getHibernateTemplate().execute(hc);
    } catch (HibernateOptimisticLockingFailureException holfe) {
        if (log.isInfoEnabled())
            log.info("An optimistic locking failure occurred while attempting to update a spreadsheet");
        throw new StaleObjectModificationException(holfe);
    }
}

From source file:org.seasar.hibernate.jpa.impl.S2HibernateDialect.java

License:Apache License

public void detach(final EntityManager em, final Object managedEntity) {
    final Session session = Session.class.cast(em.getDelegate());
    session.evict(managedEntity);
}

From source file:org.springframework.orm.hibernate3.HibernateTemplate.java

License:Apache License

@Override
public void evict(final Object entity) throws DataAccessException {
    executeWithNativeSession(new HibernateCallback<Object>() {
        @Override// w w  w .j a  va2  s.c om
        public Object doInHibernate(Session session) throws HibernateException {
            session.evict(entity);
            return null;
        }
    });
}

From source file:org.springframework.orm.hibernate3.StatelessHibernateTemplate.java

License:Apache License

public void evict(final Object entity) throws DataAccessException {
    execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            session.evict(entity);
            return null;
        }/*from  w  ww.  java  2 s . c om*/
    }, true);
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.GenericProjectDaoImpl.java

License:Open Source License

/**
 * @return the coerced project/*from   w w w  .java 2  s.c  om*/
 * @see org.squashtest.tm.service.internal.repository.CustomGenericProjectDao.squashtest.tm.service.internal.repository.CustomGenericProjectDao#coerceTemplateIntoProject(long)
 */
@Override
public Project coerceTemplateIntoProject(long templateId) {
    Session session = getCurrentSession();

    ProjectTemplate template = (ProjectTemplate) session.load(ProjectTemplate.class, templateId);
    session.flush();
    session.evict(template);

    SQLQuery query = session.createSQLQuery("update PROJECT set PROJECT_TYPE = 'P' where PROJECT_ID = :id");
    query.setParameter("id", templateId);
    final int changedRows = query.executeUpdate();
    if (changedRows != 1) {
        throw new HibernateException("Expected 1 changed row but got " + changedRows + " instead");
    }
    session.flush();

    return (Project) session.load(Project.class, templateId);
}

From source file:org.wso2.appserver.sample.chad.data.ChadPersistenceManager.java

License:Apache License

/**
 * Get administrator/*from  w  w w  .ja v a  2  s.  c om*/
 *
 * @param username
 * @return Get administrator
 */
public AdminUser getAdminUser(String username) {
    Session session = hbConfig.currentSession();
    Transaction tx = session.beginTransaction();
    AdminUser admin = null;
    try {
        Criteria criteria = session.createCriteria(AdminUser.class);
        criteria.add(Expression.eq("username", username.trim()));
        admin = (AdminUser) criteria.uniqueResult();
        session.evict(admin);
        tx.commit();
    } catch (Throwable e) {
        e.printStackTrace();
        tx.rollback();
    }
    return admin;
}