Example usage for javax.persistence PersistenceException getCause

List of usage examples for javax.persistence PersistenceException getCause

Introduction

In this page you can find the example usage for javax.persistence PersistenceException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:com.gst.accounting.financialactivityaccount.service.FinancialActivityAccountWritePlatformServiceImpl.java

@Override
public CommandProcessingResult updateGLAccountActivityMapping(Long financialActivityAccountId,
        JsonCommand command) {//from  www .j a v a  2  s  . c o  m
    try {
        this.fromApiJsonDeserializer.validateForUpdate(command.json());
        final FinancialActivityAccount financialActivityAccount = this.financialActivityAccountRepository
                .findOneWithNotFoundDetection(financialActivityAccountId);
        Map<String, Object> changes = findChanges(command, financialActivityAccount);

        if (changes.containsKey(FinancialActivityAccountsJsonInputParams.GL_ACCOUNT_ID.getValue())) {
            final Long accountId = command.longValueOfParameterNamed(
                    FinancialActivityAccountsJsonInputParams.GL_ACCOUNT_ID.getValue());
            final GLAccount glAccount = glAccountRepositoryWrapper.findOneWithNotFoundDetection(accountId);
            financialActivityAccount.updateGlAccount(glAccount);
        }

        if (changes.containsKey(FinancialActivityAccountsJsonInputParams.FINANCIAL_ACTIVITY_ID.getValue())) {
            final Integer financialActivityId = command.integerValueSansLocaleOfParameterNamed(
                    FinancialActivityAccountsJsonInputParams.FINANCIAL_ACTIVITY_ID.getValue());
            financialActivityAccount.updateFinancialActivityType(financialActivityId);
        }

        if (!changes.isEmpty()) {
            validateFinancialActivityAndAccountMapping(financialActivityAccount);
            this.financialActivityAccountRepository.save(financialActivityAccount);
        }
        return new CommandProcessingResultBuilder() //
                .withCommandId(command.commandId()) //
                .withEntityId(financialActivityAccountId) //
                .with(changes) //
                .build();
    } catch (DataIntegrityViolationException dataIntegrityViolationException) {
        handleFinancialActivityAccountDataIntegrityIssues(command,
                dataIntegrityViolationException.getMostSpecificCause(), dataIntegrityViolationException);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException ee) {
        Throwable throwable = ExceptionUtils.getRootCause(ee.getCause());
        handleFinancialActivityAccountDataIntegrityIssues(command, throwable, ee);
        return CommandProcessingResult.empty();
    }
}

From source file:com.htmlhifive.sync.resource.DefaultSynchronizer.java

/**
 * ??ID??????????.<br/>//from ww  w . ja va 2  s.co  m
 * ???????{@link DefaultSynchronizer#modify(ResourceItemCommonData)} ?????????.
 *
 * @param itemCommonId ?ID
 * @return ???
 */
@Override
public ResourceItemCommonData getNew(ResourceItemCommonDataId itemCommonId) {

    ResourceItemCommonData common = new ResourceItemCommonData(itemCommonId);

    try {
        entityManager.persist(common);
        entityManager.flush();
    } catch (PersistenceException e) {
        // ???(????)
        if (!(e.getCause() instanceof ConstraintViolationException)) {
            throw e;
        }
        common.setSyncAction(SyncAction.DUPLICATE);
    }
    return common;
}

From source file:com.gst.portfolio.savings.service.FixedDepositProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override//from   w ww.j  av a  2  s  .  c  o m
public CommandProcessingResult create(final JsonCommand command) {

    try {
        this.fromApiJsonDataValidator.validateForFixedDepositCreate(command.json());

        final FixedDepositProduct product = this.depositProductAssembler.assembleFixedDepositProduct(command);

        this.fixedDepositProductRepository.save(product);

        // save accounting mappings
        this.accountMappingWritePlatformService.createSavingProductToGLAccountMapping(product.getId(), command,
                DepositAccountType.FIXED_DEPOSIT);

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:com.vladmihalcea.HibernateOperationsOrderTest.java

@Test
public void test() {

    final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() {
        @Override/*from ww  w.  ja  v a 2  s  .c o  m*/
        public Long doInTransaction(TransactionStatus transactionStatus) {

            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);

            Product product = new Product("tvCode");
            product.setName("TV");
            product.setCompany(company);

            Image frontImage = new Image();
            frontImage.setName("front image");
            frontImage.setIndex(0);

            Image sideImage = new Image();
            sideImage.setName("side image");
            sideImage.setIndex(1);

            product.addImage(frontImage);
            product.addImage(sideImage);

            WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
            warehouseProductInfo.setQuantity(101);
            product.addWarehouse(warehouseProductInfo);

            entityManager.persist(product);
            return product.getId();
        }
    });
    try {
        transactionTemplate.execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus transactionStatus) {

                Product product = entityManager.find(Product.class, productId);
                assertEquals(2, product.getImages().size());
                Iterator<Image> imageIterator = product.getImages().iterator();

                Image frontImage = imageIterator.next();
                assertEquals("front image", frontImage.getName());
                assertEquals(0, frontImage.getIndex());
                Image sideImage = imageIterator.next();
                assertEquals("side image", sideImage.getName());
                assertEquals(1, sideImage.getIndex());

                Image backImage = new Image();
                sideImage.setName("back image");
                sideImage.setIndex(1);

                product.removeImage(sideImage);
                product.addImage(backImage);
                product.setName("tv set");

                entityManager.flush();
                return null;
            }
        });
        fail("Expected ConstraintViolationException");
    } catch (PersistenceException expected) {
        assertEquals(ConstraintViolationException.class, expected.getCause().getClass());
    }

    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            Product product = entityManager.find(Product.class, productId);
            assertEquals(2, product.getImages().size());
            Iterator<Image> imageIterator = product.getImages().iterator();

            Image frontImage = imageIterator.next();
            assertEquals("front image", frontImage.getName());
            Image sideImage = imageIterator.next();
            assertEquals("side image", sideImage.getName());

            Image backImage = new Image();
            backImage.setName("back image");
            backImage.setIndex(1);

            //http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/event/internal/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.spi.EventSource%29
            product.removeImage(sideImage);
            entityManager.flush();

            product.addImage(backImage);
            product.setName("tv set");

            entityManager.flush();
            return null;
        }
    });
}

From source file:com.gst.portfolio.savings.service.RecurringDepositProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override// w  w w .  ja v a2 s . com
public CommandProcessingResult create(final JsonCommand command) {

    try {
        this.fromApiJsonDataValidator.validateForRecurringDepositCreate(command.json());

        final RecurringDepositProduct product = this.depositProductAssembler
                .assembleRecurringDepositProduct(command);

        this.recurringDepositProductRepository.save(product);

        // save accounting mappings
        this.accountMappingWritePlatformService.createSavingProductToGLAccountMapping(product.getId(), command,
                DepositAccountType.RECURRING_DEPOSIT);

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

@SuppressWarnings("unchecked")
public List<T> list() throws ServiceException {
    try {//w ww.j a  v  a  2s .c  o m
        EntityManager entityManager = currentEntityManager();

        Criteria criteria = ((Session) entityManager.getDelegate()).createCriteria(getObjectClass());
        criteria.setMaxResults(getMaxResults());
        return criteria.setCacheable(true).list();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't get object list from database", e);
    } finally {
        closeEntityManager();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public void save(T entity) throws ServiceException {
    try {/*from  w  w w .  j  a  v  a  2s  .  com*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();

        entityManager.persist(entity);

        commitTransaction();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't update object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public T update(T entity) throws ServiceException {
    try {//w w w.  j av a  2s .  c o m
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();
        T loadedObject = entityManager.find(getObjectClass(), getObjectId(entity));
        T mergedEntity = merge(loadedObject, entity);
        T updatedEntity = entityManager.merge(mergedEntity);
        commitTransaction();
        return updatedEntity;
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't update object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:com.healthcit.cacure.web.controller.question.QuestionElementEditController.java

/**
 * Process data entered by user/*from  ww  w  .  j  a va2s. co m*/
 * @param question
 * @param formId
 * @return
 */
@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) FormElement qElement, BindingResult result,
        @ModelAttribute(LOOKUP_DATA) Map lookupData, SessionStatus status, HttpServletRequest req,
        @RequestParam(value = IS_EXTERNAL, required = false) String isExternal) {

    validateEditOperation(qElement);

    log.debug("QuestionElement: " + qElement.toString());

    log.debug(qElement.toString());
    Long formId = null;
    boolean isNew = qElement.isNew();
    try {

        if (isNew) {
            //The ExternalQuestionElement can only be created via import.
            formId = getFormId();
            qaManager.addNewFormElement(qElement, formId);
        } else {
            formId = qElement.getForm().getId();

            if (qElement instanceof ExternalQuestionElement) {
                //unlink because of modifications
                ((ExternalQuestionElement) qElement).unlink();
            }
            qaManager.updateFormElement(qElement);

        }
    } catch (PersistenceException e) {
        Throwable t = e.getCause();
        if (t instanceof GenericJDBCException) {
            String message = ((GenericJDBCException) t).getSQLException().getNextException().getMessage();
            if (message.indexOf("short name already exists") > -1) {
                if (isNew) {
                    qElement.resetId();
                    qElement.getDescriptionList().clear();
                }
                int beginIndex = message.indexOf('[');
                int endIndex = message.indexOf(']');
                String shortName = message.substring(beginIndex + 1, endIndex);
                Object[] params = { shortName };
                result.rejectValue("question.shortName", "notunique.shortName", params,
                        "Short name is not unique");
                return new ModelAndView("questionEdit");
            } else {
                throw e;
            }
        } else {
            throw e;
        }
    }

    qElement.setCategories(prepareCategories(req, lookupData));
    //      TODO Save 2 times is not good idea. We clear constraints by second update (see implementation)
    //      Changes to attached to session object save automatically. So categories are seved
    //      qaManager.updateFormElement(qElement);

    // after question is saved - return to question listing
    return new ModelAndView(new RedirectView(Constants.QUESTION_LISTING_URI + "?formId=" + formId, true));
}

From source file:com.gst.portfolio.savings.service.SavingsProductWritePlatformServiceJpaRepositoryImpl.java

@Transactional
@Override/*  www.j a  va 2s  .  c  o  m*/
public CommandProcessingResult create(final JsonCommand command) {

    try {
        this.fromApiJsonDataValidator.validateForCreate(command.json());

        final SavingsProduct product = this.savingsProductAssembler.assemble(command);

        this.savingProductRepository.save(product);

        // save accounting mappings
        this.accountMappingWritePlatformService.createSavingProductToGLAccountMapping(product.getId(), command,
                DepositAccountType.SAVINGS_DEPOSIT);

        // check if the office specific products are enabled. If yes, then
        // save this savings product against a specific office
        // i.e. this savings product is specific for this office.
        fineractEntityAccessUtil.checkConfigurationAndAddProductResrictionsForUserOffice(
                FineractEntityAccessType.OFFICE_ACCESS_TO_SAVINGS_PRODUCTS, product.getId());

        return new CommandProcessingResultBuilder() //
                .withEntityId(product.getId()) //
                .build();
    } catch (final DataAccessException e) {
        handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
        return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
        Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
        handleDataIntegrityIssues(command, throwable, dve);
        return CommandProcessingResult.empty();
    }
}