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.openvpms.component.business.dao.hibernate.im.party.PartyDOTestCase.java

License:Open Source License

/**
 * Verifies that deleting the source of an EntityLink doesn't delete the target.
 *///from   w  ww .  j  a v a2  s .c o  m
@Test
public void testDeleteEntityLinkSource() {
    Session session = getSession();
    Transaction tx = session.beginTransaction();

    PartyDO source = createPerson();
    PartyDO target = createPerson();
    EntityLinkDO link = createEntityLink(source, target);
    session.saveOrUpdate(source);
    session.saveOrUpdate(target);
    tx.commit();
    long version = target.getVersion();

    session.evict(source);
    source = session.load(PartyDOImpl.class, source.getId());
    assertTrue(source.getEntityLinks().contains(link));
    assertNotNull(session.load(EntityLinkDOImpl.class, link.getId()));

    tx = session.beginTransaction();
    session.delete(source);
    tx.commit();

    assertNull(session.get(PartyDOImpl.class, source.getId()));
    assertNull(session.get(EntityLinkDOImpl.class, link.getId()));

    session.evict(target);
    target = session.load(PartyDOImpl.class, target.getId());
    assertEquals(version, target.getVersion()); // verify the target hasn't changed
}

From source file:org.pentaho.platform.repository.datasource.DatasourceMgmtService.java

License:Open Source License

public void createDatasource(IDatasource newDatasource)
        throws DuplicateDatasourceException, DatasourceMgmtServiceException {
    Session session = HibernateUtil.getSession();
    if (newDatasource != null) {
        if (getDatasource(newDatasource.getName()) == null) {
            try {
                session.setCacheMode(CacheMode.REFRESH);
                IPasswordService passwordService = PentahoSystem.getObjectFactory().get(IPasswordService.class,
                        null);/*  w  w  w.ja v  a 2s .  c  o  m*/
                newDatasource.setPassword(passwordService.encrypt(newDatasource.getPassword()));
                session.save(newDatasource);
            } catch (ObjectFactoryException objface) {
                throw new DatasourceMgmtServiceException(Messages
                        .getErrorString("DatasourceMgmtService.ERROR_0009_UNABLE_TO_INIT_PASSWORD_SERVICE")); //$NON-NLS-1$
            } catch (PasswordServiceException pse) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0007_UNABLE_TO_ENCRYPT_PASSWORD"), //$NON-NLS-1$
                        pse);
            } catch (HibernateException ex) {
                session.evict(newDatasource);
                throw new DatasourceMgmtServiceException(
                        Messages.getErrorString("DatasourceMgmtService.ERROR_0001_UNABLE_TO_CREATE_DATASOURCE", //$NON-NLS-1$
                                newDatasource.getName()),
                        ex);
            } finally {
                session.setCacheMode(CacheMode.NORMAL);
            }
        } else {
            throw new DuplicateDatasourceException(Messages.getErrorString(
                    "DatasourceMgmtService.ERROR_0005_DATASOURCE_ALREADY_EXIST", newDatasource.getName()));//$NON-NLS-1$
        }
    } else {
        throw new DatasourceMgmtServiceException(
                Messages.getErrorString("DatasourceMgmtService.ERROR_0010_NULL_DATASOURCE_OBJECT"));//$NON-NLS-1$
    }
    session.setCacheMode(CacheMode.NORMAL);
    HibernateUtil.flushSession();
}

From source file:org.riotfamily.media.cleanup.HibernateCleanUpTask.java

License:Apache License

private void delete(final Session session, final Long id) {
    try {/*www .j av a2s.  c o  m*/
        RiotFile file = transactionTemplate.execute(new TransactionCallback<RiotFile>() {
            public RiotFile doInTransaction(TransactionStatus status) {
                log.debug("Deleting orphaned file: " + id);
                RiotFile file = (RiotFile) session.load(RiotFile.class, id);
                session.delete(file);
                return file;
            }
        });
        session.evict(file);
    } catch (HibernateException e) {
        log.error("Failed to delete RiotFile " + id, e);
    }
}

From source file:org.sakaiproject.component.gradebook.BaseHibernateManager.java

License:Educational Community License

protected void updateAssignment(Assignment assignment, Session session)
        throws ConflictingAssignmentNameException, 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(assignment);

    Assignment asnFromDb = (Assignment) session.load(Assignment.class, assignment.getId());
    List conflictList = ((List) session.createQuery(
            "select go from GradableObject as go where go.name = ? and go.gradebook = ? and go.removed=false and go.id != ?")
            .setString(0, assignment.getName()).setEntity(1, assignment.getGradebook())
            .setLong(2, assignment.getId().longValue()).list());
    int numNameConflicts = conflictList.size();
    if (numNameConflicts > 0) {
        throw new ConflictingAssignmentNameException(
                "You can not save multiple assignments in a gradebook with the same name");
    }/*from ww  w. j  a va  2s  .c om*/

    session.evict(asnFromDb);
    session.update(assignment);
}

From source file:org.sakaiproject.component.gradebook.BaseHibernateManager.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. java  2  s.  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 can not 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.component.gradebook.BaseHibernateManager.java

License:Educational Community License

protected void updateCategory(Category category, Session session)
        throws ConflictingAssignmentNameException, HibernateException {
    session.evict(category);
    Category persistentCat = (Category) session.load(Category.class, category.getId());

    List conflictList = ((List) session.createQuery(
            "select ca from Category as ca where ca.name = ? and ca.gradebook = ? and ca.id != ? and ca.removed=false")
            .setString(0, category.getName()).setEntity(1, category.getGradebook())
            .setLong(2, category.getId().longValue()).list());
    int numNameConflicts = conflictList.size();
    if (numNameConflicts > 0) {
        throw new ConflictingCategoryNameException(
                "You can not save multiple category in a gradebook with the same name");
    }/*from  www.j  a  va2 s .c o m*/
    if (category.getWeight().doubleValue() > 1 || category.getWeight().doubleValue() < 0) {
        throw new IllegalArgumentException(
                "weight for category is greater than 1 or less than 0 in updateCategory of BaseHibernateManager");
    }
    session.evict(persistentCat);
    session.update(category);
}

From source file:org.sakaiproject.component.gradebook.BaseHibernateManager.java

License:Educational Community License

public void updateCategory(final Category category)
        throws ConflictingCategoryNameException, StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            session.evict(category);
            Category persistentCat = (Category) session.load(Category.class, category.getId());
            List conflictList = ((List) session.createQuery(
                    "select ca from Category as ca where ca.name = ? and ca.gradebook = ? and ca.id != ? and ca.removed=false")
                    .setString(0, category.getName()).setEntity(1, category.getGradebook())
                    .setLong(2, category.getId().longValue()).list());
            int numNameConflicts = conflictList.size();
            if (numNameConflicts > 0) {
                throw new ConflictingCategoryNameException(
                        "You can not save multiple category in a gradebook with the same name");
            }/*  w w w. ja  v  a2  s.  c o  m*/
            if (category.getWeight().doubleValue() > 1 || category.getWeight().doubleValue() < 0) {
                throw new IllegalArgumentException(
                        "weight for category is greater than 1 or less than 0 in updateCategory of BaseHibernateManager");
            }
            session.evict(persistentCat);
            session.update(category);
            return null;
        }
    };
    try {
        getHibernateTemplate().execute(hc);
    } catch (Exception e) {
        throw new StaleObjectModificationException(e);
    }
}

From source file:org.sakaiproject.evaluation.dao.EvaluationDaoImpl.java

License:Educational Community License

/**
 * This really does not work for most cases so be very careful with it
 * @param object/*from   w  w  w. ja  v  a  2 s  . co  m*/
 */
protected void forceEvict(Serializable object) {
    boolean active = false;
    try {
        Session session = currentSession();
        if (session.isOpen() && session.isConnected()) {
            if (session.contains(object)) {
                active = true;
                session.evict(object);
            }
        } else {
            LOG.warn("Session is not open OR not connected, cannot evict objects");
        }
        if (!active) {
            LOG.info("Unable to evict object (" + object.getClass().getName()
                    + ") from session, it is not persistent: " + object);
        }
    } catch (DataAccessResourceFailureException | IllegalStateException | HibernateException e) {
        LOG.warn("Failure while attempting to evict object (" + object.getClass().getName() + ") from session",
                e);
    }
}

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

License:Educational Community License

public void updateAssignment(final Assignment assignment)
        throws ConflictingAssignmentNameException, StaleObjectModificationException {

    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {

            session.evict(assignment);
            session.update(assignment);// ww w.  ja v  a 2 s .  co m

            /*
             * GRBK-913 : flushing the session so that we don't need to further evict the assignment object
             * in case an exception occurs. In the exception handling bellow, we get the assignment from DB and compare
             * it against the passed in assignment object
             */
            session.flush();
            return null;
        }
    };

    try {

        getHibernateTemplate().execute(hc);

    } catch (HibernateOptimisticLockingFailureException e) {

        // GRBK-913
        /*
         * Getting the current assignment from the DB so that we can compare it 
         * against the assignment instance that was supposed to be saved.
         */
        Assignment persistedAssignment = getAssignment(assignment.getId());

        if (!hasEqualValues(assignment, persistedAssignment)) {

            if (log.isInfoEnabled())
                log.info("An optimistic locking failure occurred while attempting to update an assignment", e);
            throw new StaleObjectModificationException(e);
        } else {

            if (log.isInfoEnabled())
                log.info(
                        "An optimistic locking failure occurred while attempting to update an assignment, but the assignments have the same values",
                        e);
        }
    }
}

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

License:Educational Community License

public void updateCategory(final Category category)
        throws ConflictingCategoryNameException, StaleObjectModificationException {
    HibernateCallback hc = new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            session.evict(category);
            Category persistentCat = (Category) session.load(Category.class, category.getId());
            List conflictList = ((List) session.createQuery(
                    "select ca from Category as ca where ca.name = ? and ca.gradebook = ? and ca.id != ? and (ca.removed=false or ca.removed is null)")
                    .setString(0, category.getName()).setEntity(1, category.getGradebook())
                    .setLong(2, category.getId().longValue()).list());
            int numNameConflicts = conflictList.size();
            if (numNameConflicts > 0) {
                throw new ConflictingCategoryNameException(
                        "You cannot save multiple categories in a gradebook with the same name");
            }/*from  ww  w  .j  av  a  2s  .c om*/
            if (category.getWeight().doubleValue() > 1 || category.getWeight().doubleValue() < 0) {
                throw new IllegalArgumentException(
                        "weight for category is greater than 1 or less than 0 in updateCategory of BaseHibernateManager");
            }
            session.evict(persistentCat);
            session.update(category);
            return null;
        }
    };
    try {
        getHibernateTemplate().execute(hc);
    } catch (Exception e) {
        throw new StaleObjectModificationException(e);
    }
}