Example usage for org.springframework.transaction.annotation Propagation REQUIRES_NEW

List of usage examples for org.springframework.transaction.annotation Propagation REQUIRES_NEW

Introduction

In this page you can find the example usage for org.springframework.transaction.annotation Propagation REQUIRES_NEW.

Prototype

Propagation REQUIRES_NEW

To view the source code for org.springframework.transaction.annotation Propagation REQUIRES_NEW.

Click Source Link

Document

Create a new transaction, and suspend the current transaction if one exists.

Usage

From source file:es.emergya.bbdd.dao.UsuarioHome.java

@Transactional(readOnly = false, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public boolean saveOrUpdate(Usuario entity) {
    log.trace("saveOrUpdate(" + entity + ")");
    if (entity == null)
        throw new NullPointerException("No se puede guardar un usuario nulo");
    org.hibernate.Session currentSession = getSession();
    currentSession.clear();//from   w  w w . j  av  a 2s  . c  om
    Object e = null;
    try {
        if (entity.getId() == null || (entity.getId() != null && this.get(entity.getId()) == null)) {
            log.trace("Tenemos que crear un usuario nuevo");
            e = entity;
        } else {
            log.trace("Hacemos update sobre un usuario ya antiguo");
            e = currentSession.merge(entity);
        }
    } catch (Throwable t) {
        log.error("Tiene toda la pinta de que estamos guardando algo ya borrado", t);
    }
    if (e == null) {
        log.debug("Error al mergear");
        throw new NullPointerException("No se puede guardar el usuario, es nulo");
    }
    currentSession.saveOrUpdate(e);
    log.trace("saved");
    return true;
}

From source file:es.emergya.bbdd.dao.RolHome.java

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = Throwable.class)
public boolean delete(Rol rol) {
    if (rol == null || rol.getId() == null)
        return true;

    Session currentSession = getSession();
    currentSession.clear();/*from w w  w .j a  va2  s . c o m*/
    try {
        rol = this.get(rol.getId());
    } catch (Throwable t) {
        log.error("Tiene toda la pinta de que estamos borrando un objeto ya borrado", t);
    }

    if (rol != null && (rol.getUsuarios() == null || rol.getUsuarios().size() == 0)) {
        if (rol.getFlotas() != null) {
            for (Flota f : rol.getFlotas()) {
                f.getRoles().remove(rol);
                currentSession.saveOrUpdate(f);
            }
        }
        this.remove(rol.getId());
        return true;
    }
    return false;
}

From source file:es.tid.fiware.rss.dao.impl.test.DbeSystemPropertiesDaoImplTest.java

@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void testhDeleteAll() {
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setPropagationBehavior(Propagation.REQUIRES_NEW.value());
    TransactionStatus status = transactionManager.getTransaction(def);
    dbeSystemPropertiesDao.deleteAll();/*from www .j  a va2 s  .  co m*/
    transactionManager.commit(status);
    Assert.assertTrue(dbeSystemPropertiesDao.getAll().size() == 0);
}

From source file:architecture.ee.web.site.DefaultWebSiteManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void createWebSite(WebSite webSite) throws WebSiteAlreadyExistsExcaption {

    if (StringUtils.isNotEmpty(webSite.getName())
            && webSiteDao.findWebSitesByName(webSite.getName()).size() > 0) {
        throw new WebSiteAlreadyExistsExcaption();
    }//w w  w .ja va2s . co m

    if (StringUtils.isNotEmpty(webSite.getUrl()) && webSiteDao.findWebSitesByUrl(webSite.getUrl()).size() > 0) {
        throw new WebSiteAlreadyExistsExcaption();
    }

    webSiteDao.createWebSite(webSite);
}

From source file:architecture.user.DefaultCompanyManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public Company createCompany(String name, String displayName, String domainName, String description)
        throws CompanyAlreadyExistsException {
    try {/*from w w  w.  j a va 2 s.co m*/
        getCompany(name);
        throw new CompanyAlreadyExistsException();
    } catch (CompanyNotFoundException unfe) {
        if (!StringUtils.isEmpty(domainName)) {
            try {
                getCompanyByDomainName(domainName);
                throw new CompanyAlreadyExistsException();
            } catch (CompanyNotFoundException e) {
                // ignore ..

            }
        }
        Company company = new CompanyTemplate();
        company.setDescription(description);
        company.setDisplayName(displayName);
        company.setName(name);
        company.setDomainName(domainName);
        Date now = new Date();
        company.setCreationDate(now);
        company.setModifiedDate(now);
        companyDao.createCompany(company);
        return company;
    }
}

From source file:org.trpr.platform.core.impl.persistence.PersistenceDelegate.java

/**
 * Deletes the specified PersistentEntity instances using the specified PersistenceProvider instances, matched by index positions. 
 * Note that this method is transactional by default.
 * It is advisable to use {@link PersistenceManagerProvider#makeTransient(PersistentEntity[])} instead of calling this method directly.
 * @param entities the PersistentEntity instances to delete
 * @param providers the PersistenceProvider instances to use in delete
 * @return  PersistentEntity instances that were deleted
 * @throws PersistenceException in case of deletion errors
 *//*w  w  w  .ja va  2  s . c  o  m*/
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.DEFAULT, rollbackForClassName = {
        "Exception" })
public void makeTransient(PersistentEntity[] entities, PersistenceProvider[] providers)
        throws PersistenceException {
    for (int i = 0; i < entities.length; i++) {
        providers[i].makeTransient(entities[i]);
    }
}

From source file:architecture.ee.web.community.streams.DefaultPhotoStreamsManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void addImage(Image image, User creator) {
    PhotoImpl photoToUse = new PhotoImpl(RandomStringUtils.random(64, true, true), image.getImageId(), true,
            creator);//from w  ww . j  a  v  a 2s  .c o  m
    Date now = new Date();
    photoToUse.setCreationDate(now);
    photoToUse.setModifiedDate(now);

    this.streamsDao.addPhoto(photoToUse);
}

From source file:com.ibm.asset.trails.service.impl.ReconServiceImpl.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void reconcileByAlert(Long alertId, InstalledSoftware parentInstalledSoftware, Recon reconRequest,
        String remoteUser, String comments, Account account) {
    AlertUnlicensedSw alert = findAlertById(alertId);
    boolean bReconcileValidation = reconcileValidate(alert);
    if (bReconcileValidation) {
        Reconcile reconcile = findReconcile(alert);
        clearUsedLicenses(reconcile, remoteUser);
        ReconcileH reconcileH = findReconcileHistory(alert);
        clearUsedLicenseHistories(reconcileH);
        reconcile = updateReconcile(reconRequest, reconcile, alert, remoteUser, new HashSet<UsedLicense>());
        reconcileH = updateReconcileH(reconcile, reconcileH, alert, new HashSet<UsedLicenseHistory>());
        alert.setReconcile(reconcile);/*from   w w  w  . j av  a  2  s  .  c  om*/
        alert.setReconcileH(reconcileH);
        closeAlert(alert);
    }
}

From source file:com.google.ie.business.dao.impl.IdeaDaoImpl.java

/**
 * Update of the idea vote points of the given idea.
 * /*from   ww w . ja  va 2s.c o m*/
 * @param idea Idea object containing updated status and key.
 * @return boolean return true or false on the basis of successful update.
 */
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public boolean updateIdeaPoints(final Idea idea) {
    Idea originalIdea = getJdoTemplate().getObjectById(Idea.class, idea.getKey());
    boolean flag = false;
    if (originalIdea != null) {
        originalIdea.setTotalVotes(idea.getTotalVotes());
        originalIdea.setTotalPositiveVotes(idea.getTotalPositiveVotes());
        originalIdea.setTotalNegativeVotes(idea.getTotalNegativeVotes());
        if (getJdoTemplate().makePersistent(originalIdea) != null) {
            flag = true;
        }
    }
    return flag;
}

From source file:com.epam.catgenome.manager.ProjectManagerTest.java

@Test
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void testSaveLoadDeleteProject() throws IOException, InterruptedException, NoSuchAlgorithmException,
        VcfReadingException, FeatureIndexException {
    VcfFile file = addVcfFile(TEST_VCF_FILE_NAME1, TEST_VCF_FILE_PATH);
    BiologicalDataItem item = new BiologicalDataItem();
    item.setId(file.getBioDataItemId());

    Project project = new Project();
    project.setName(TEST_PROJECT_NAME);/*w  ww .  jav  a2 s .c o  m*/
    project.setItems(Arrays.asList(new ProjectItem(new BiologicalDataItem(testReference.getBioDataItemId())),
            new ProjectItem(item)));

    projectManager.saveProject(project);

    Project loadedProject = projectManager.loadProject(project.getId());
    Assert.assertNotNull(loadedProject);
    Assert.assertFalse(loadedProject.getItems().isEmpty());

    // load my projects
    List<Project> myProjects = projectManager.loadTopLevelProjectsForCurrentUser();
    Assert.assertTrue(myProjects.stream().allMatch(p -> !p.getItems().isEmpty()));

    VcfFile file2 = addVcfFile(TEST_VCF_FILE_NAME2, TEST_VCF_FILE_PATH);
    BiologicalDataItem item2 = new BiologicalDataItem();
    item2.setId(file2.getBioDataItemId());
    loadedProject.getItems().add(new ProjectItem(item2));

    projectManager.saveProject(loadedProject);

    loadedProject = projectManager.loadProject(project.getId());
    Assert.assertEquals(loadedProject.getItems().size(), 3);

    loadedProject.getItems().remove(2);
    projectManager.saveProject(loadedProject);

    loadedProject = projectManager.loadProject(project.getId());
    Assert.assertEquals(loadedProject.getItems().size(), 2);
    Assert.assertEquals(TEST_VCF_FILE_NAME1, loadedProject.getItems().get(1).getBioDataItem().getName());

    loadedProject.getItems().get(0).setHidden(true);
    projectManager.saveProject(loadedProject);

    loadedProject = projectManager.loadProject(project.getId());
    Assert.assertEquals(loadedProject.getItems().size(), 2);
    Assert.assertTrue(loadedProject.getItems().get(0).getHidden());

    // add a bookmark
    Bookmark bookmark = new Bookmark();
    bookmark.setOpenedItems(Collections.singletonList(item));
    bookmark.setStartIndex(1);
    bookmark.setEndIndex(BOOKMARK_END_INDEX);
    bookmark.setChromosome(testChromosome);
    bookmark.setName("testBookmark");

    bookmarkManager.saveBookmark(bookmark);

    List<Bookmark> loadedBookmarks = bookmarkManager.loadBookmarksByProject();

    Assert.assertNotNull(loadedBookmarks);
    Assert.assertFalse(loadedBookmarks.isEmpty());

    Bookmark loadedBookmark = loadedBookmarks.get(0);

    loadedBookmark = bookmarkManager.loadBookmark(loadedBookmark.getId());
    Assert.assertFalse(loadedBookmark.getOpenedItems().isEmpty());
    Assert.assertEquals(BiologicalDataItem.getBioDataItemId(loadedBookmark.getOpenedItems().get(0)),
            item.getId());

    // Now delete project
    projectManager.deleteProject(project.getId(), false);
    try {
        projectManager.loadProject(project.getId());
        Assert.fail("No exception happened, but should happen");
    } catch (IllegalArgumentException e) {
        // success, nothing to do here
        logger.debug("Deleted successfully, nothing to do here");
    }

    File dir = new File(baseDirPath + "/projects/" + project.getId());
    Assert.assertFalse(dir.exists());
}