Java Examples for org.apache.ibatis.exceptions.PersistenceException

The following java examples will help you to understand the usage of org.apache.ibatis.exceptions.PersistenceException. These source code samples are taken from different open source projects.

Example 1
Project: mybatis-3-master  File: SelectKeyTest.java View source code
@Test(expected = PersistenceException.class)
public void testSeleckKeyReturnsNoData() {
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        Map<String, String> parms = new HashMap<String, String>();
        parms.put("name", "Fred");
        int rows = sqlSession.insert("org.apache.ibatis.submitted.selectkey.Table2.insertNoValuesInSelectKey", parms);
        assertEquals(1, rows);
        assertNull(parms.get("id"));
    } finally {
        sqlSession.close();
    }
}
Example 2
Project: checklistbank-master  File: NameUsageReparser.java View source code
@Transactional(exceptionMessage = "names inserts failed", executorType = ExecutorType.REUSE)
private void writeNames(List<ScientificParsedName> pNames) {
    for (ScientificParsedName spn : pNames) {
        try {
            nameMapper.create2(spn.sciname.getKey(), spn.pn);
        } catch (PersistenceException e) {
            Throwable cause = e.getCause() != null ? e.getCause() : e;
            LOG.warn("Failed to persist name {}: {}", spn.pn, cause.getMessage());
            nameMapper.failed(spn.sciname.getKey(), spn.pn.getScientificName(), spn.pn.getRank());
        } catch (Exception e) {
            LOG.error("Unexpected error persisting name {}", spn.pn, e);
            nameMapper.failed(spn.sciname.getKey(), spn.sciname.getScientificName(), spn.sciname.getRank());
        }
    }
}
Example 3
Project: camel-master  File: MyBatisInsertWithRollbackTest.java View source code
@Test
public void testInsert() throws Exception {
    getMockEndpoint("mock:commit").expectedMessageCount(0);
    getMockEndpoint("mock:rollback").expectedMessageCount(1);
    getMockEndpoint("mock:rollback").message(0).body().isEqualTo(null);
    getMockEndpoint("mock:rollback").message(0).header(Exchange.EXCEPTION_CAUGHT).isInstanceOf(PersistenceException.class);
    template.sendBody("direct:start", null);
    assertMockEndpointsSatisfied();
    // there should be still 2 rows
    Integer rows = template.requestBody("mybatis:count?statementType=SelectOne", null, Integer.class);
    assertEquals("There should be 2 rows", 2, rows.intValue());
}
Example 4
Project: mybatis-shards-master  File: ShardImpl.java View source code
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    final SqlSession sqlSession = SqlSessionUtils.getSqlSession(ShardImpl.this.sqlSessionFactory, ShardImpl.this.executorType, ShardImpl.this.exceptionTranslator);
    try {
        Object result = method.invoke(sqlSession, args);
        if (!isSqlSessionTransactional(sqlSession, ShardImpl.this.sqlSessionFactory)) {
            // force commit even on non-dirty sessions because some databases require
            // a commit/rollback before calling close()
            sqlSession.commit(true);
        }
        return result;
    } catch (Throwable t) {
        Throwable unwrapped = unwrapThrowable(t);
        if (ShardImpl.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
            Throwable translated = ShardImpl.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
            if (translated != null) {
                unwrapped = translated;
            }
        }
        throw unwrapped;
    } finally {
        closeSqlSession(sqlSession, ShardImpl.this.sqlSessionFactory);
    }
}
Example 5
Project: MybatisSpring2.5.X-master  File: SqlSessionUtils.java View source code
/**
     * {@inheritDoc}
     */
@Override
public void beforeCommit(boolean readOnly) {
    // If there is no tx active data will be rolled back so there is no need to flush batches
    if (this.holder.getExecutorType() == ExecutorType.BATCH && isActualTransactionActive()) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("Transaction synchronization flushing SqlSession [" + this.holder.getSqlSession() + "]");
            }
            this.holder.getSqlSession().flushStatements();
        } catch (PersistenceException p) {
            if (this.holder.getPersistenceExceptionTranslator() != null) {
                DataAccessException translated = this.holder.getPersistenceExceptionTranslator().translateExceptionIfPossible(p);
                if (translated != null) {
                    throw translated;
                }
            }
            throw p;
        }
    }
}
Example 6
Project: mmp-master  File: SmallIntArrayTest.java View source code
@Test
public void testIntegerArrayWithTooLargeValue() {
    String testName = "too large value test";
    boolean exceptionWasCaught = false;
    IntegerArrayBean t = new IntegerArrayBean();
    Integer[] intArray = new Integer[] { 1, Integer.MAX_VALUE, 3 };
    t.setIntegerArray(intArray);
    t.setName(testName);
    try {
        session.insert("test.insertSmallIntArray", t);
    } catch (PersistenceException e) {
        log.info("caught expected exception: ", e);
        exceptionWasCaught = true;
    } finally {
        session.rollback(true);
    }
    Assert.assertTrue(exceptionWasCaught, "Integers larger than PostgreSQL smallint need to throw exeption.");
}
Example 7
Project: aurora-master  File: RowGarbageCollector.java View source code
@Timed("row_garbage_collector_run")
@VisibleForTesting
@Override
public void runOneIteration() {
    LOG.info("Scanning database tables for unreferenced rows.");
    long startCount = deletedCount.get();
    for (Class<? extends GarbageCollectedTableMapper> tableClass : TABLES) {
        storage.write((NoResult.Quiet)  storeProvider -> {
            try (SqlSession session = sessionFactory.openSession(true)) {
                GarbageCollectedTableMapper table = session.getMapper(tableClass);
                for (long rowId : table.selectAllRowIds()) {
                    try {
                        table.deleteRow(rowId);
                        deletedCount.incrementAndGet();
                    } catch (PersistenceException e) {
                    }
                }
            }
        });
    }
    LOG.info("Deleted {} unreferenced rows.", Long.valueOf(deletedCount.get() - startCount));
}
Example 8
Project: xbpm5-master  File: ConcurrentEngineUsageTest.java View source code
protected void retryStartProcess(String runningUser) {
    int retries = MAX_RETRIES;
    int timeout = 200;
    boolean success = false;
    while (retries > 0 && !success) {
        try {
            runtimeService.startProcessInstanceByKey("concurrentProcess", Collections.singletonMap("assignee", (Object) runningUser));
            success = true;
        } catch (PersistenceException pe) {
            retries = retries - 1;
            log.debug("Retrying process start - " + (MAX_RETRIES - retries));
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ignore) {
            }
            timeout = timeout + 200;
        }
    }
    if (success == false) {
        log.debug("Retrying process start FAILED " + MAX_RETRIES + " times");
    }
}
Example 9
Project: MyBatisDAOHelper-master  File: MyBatisDAO.java View source code
/** 
     *  Default get by id method. 
     *  </br></br> 
     *  Almost all objects in the db will 
     *  need this (except mapping tables for multiple joins, which you 
     *  probably shouldn't even have as objects in your model, since proper 
     *  MyBatis mappings can take care of that).
     *  </br></br>
     *  Example: 
     *  </br>
     *  If your DAO object is called CarInfo.java, 
     *  the corresponding mapper query id should be: <select id="getCarInfo" ...  
     */
public T get(PK id) throws PersistenceException {
    SqlSession session = sf.openSession();
    T obj = null;
    try {
        //If the object's calls name is AddressType.java, this matches the mapper query id: "namespace.getAddressType"
        String query = NAMESPACE + "." + PREFIX_SELECT_QUERY + this.type.getSimpleName();
        obj = (T) session.selectOne(query, id);
    } finally {
        session.close();
    }
    return obj;
}
Example 10
Project: syncope-master  File: RestServiceExceptionMapper.java View source code
@Override
public Response toResponse(final Exception ex) {
    LOG.error("Exception thrown", ex);
    ResponseBuilder builder;
    if (ex instanceof AccessDeniedException) {
        // leaves the default exception processing to Spring Security
        builder = null;
    } else if (ex instanceof SyncopeClientException) {
        SyncopeClientException sce = (SyncopeClientException) ex;
        builder = sce.isComposite() ? getSyncopeClientCompositeExceptionResponse(sce.asComposite()) : getSyncopeClientExceptionResponse(sce);
    } else if (ex instanceof DelegatedAdministrationException) {
        builder = builder(ClientExceptionType.DelegatedAdministration, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof EntityExistsException || ex instanceof DuplicateException || ex instanceof PersistenceException && ex.getCause() instanceof EntityExistsException) {
        builder = builder(ClientExceptionType.EntityExists, getJPAMessage(ex instanceof PersistenceException ? ex.getCause() : ex));
    } else if (ex instanceof DataIntegrityViolationException || ex instanceof JpaSystemException) {
        builder = builder(ClientExceptionType.DataIntegrityViolation, getJPAMessage(ex));
    } else if (ex instanceof ConnectorException) {
        builder = builder(ClientExceptionType.ConnectorException, ExceptionUtils.getRootCauseMessage(ex));
    } else if (ex instanceof NotFoundException) {
        builder = builder(ClientExceptionType.NotFound, ExceptionUtils.getRootCauseMessage(ex));
    } else {
        builder = processInvalidEntityExceptions(ex);
        if (builder == null) {
            builder = processBadRequestExceptions(ex);
        }
        // process JAX-RS validation errors
        if (builder == null && ex instanceof ValidationException) {
            builder = builder(validationEM.toResponse((ValidationException) ex)).header(RESTHeaders.ERROR_CODE, ClientExceptionType.RESTValidation.name()).header(RESTHeaders.ERROR_INFO, ClientExceptionType.RESTValidation.getInfoHeaderValue(ExceptionUtils.getRootCauseMessage(ex)));
            ErrorTO error = new ErrorTO();
            error.setStatus(ClientExceptionType.RESTValidation.getResponseStatus().getStatusCode());
            error.setType(ClientExceptionType.RESTValidation);
            error.getElements().add(ExceptionUtils.getRootCauseMessage(ex));
            builder.entity(error);
        }
        // ...or just report as InternalServerError
        if (builder == null) {
            builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).header(RESTHeaders.ERROR_INFO, ClientExceptionType.Unknown.getInfoHeaderValue(ExceptionUtils.getRootCauseMessage(ex)));
            ErrorTO error = new ErrorTO();
            error.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
            error.setType(ClientExceptionType.Unknown);
            error.getElements().add(ExceptionUtils.getRootCauseMessage(ex));
            builder.entity(error);
        }
    }
    return builder == null ? null : builder.build();
}
Example 11
Project: OpenIDM-master  File: ProcessDefinitionResource.java View source code
@Override
public Promise<ResourceResponse, ResourceException> deleteInstance(Context context, String resourceId, DeleteRequest request) {
    try {
        Authentication.setAuthenticatedUserId(context.asContext(SecurityContext.class).getAuthenticationId());
        ProcessDefinitionEntity processDefinition = (ProcessDefinitionEntity) processEngine.getRepositoryService().getProcessDefinition(resourceId);
        if (processDefinition != null) {
            ResourceResponse r = convertInstance(processDefinition, request.getFields());
            processEngine.getRepositoryService().deleteDeployment(processDefinition.getDeploymentId(), false);
            return r.asPromise();
        } else {
            throw new NotFoundException();
        }
    } catch (ActivitiObjectNotFoundException ex) {
        return new NotFoundException(ex.getMessage()).asPromise();
    } catch (PersistenceException ex) {
        return new ConflictException("The process definition has running instances, can not be deleted").asPromise();
    } catch (ResourceException e) {
        return e.asPromise();
    } catch (Exception ex) {
        return new InternalServerErrorException(ex.getMessage()).asPromise();
    }
}
Example 12
Project: spring-master  File: MyBatisSpringTest.java View source code
@Test
public void testBatchWithError() {
    try {
        setupBatchStatements();
        session = SqlSessionUtils.getSqlSession(sqlSessionFactory, ExecutorType.BATCH, exceptionTranslator);
        session.getMapper(TestMapper.class).insertTest("test1");
        session.getMapper(TestMapper.class).insertTest("test2");
        session.update("org.mybatis.spring.TestMapper.insertFail");
        session.getMapper(TestMapper.class).insertTest("test3");
        assertThrows(PersistenceException.class, () -> session.commit(true));
    } finally {
        SqlSessionUtils.closeSqlSession(session, sqlSessionFactory);
    }
}
Example 13
Project: sonarqube-master  File: OrganizationDaoTest.java View source code
@Test
public void insert_fails_if_row_with_uuid_already_exists() {
    insertOrganization(ORGANIZATION_DTO_1);
    OrganizationDto dto = new OrganizationDto().setUuid(ORGANIZATION_DTO_1.getUuid()).setKey("other key").setName("other name").setCreatedAt(2_999_000L).setUpdatedAt(2_888_000L);
    expectedException.expect(PersistenceException.class);
    underTest.insert(dbSession, dto, false);
}
Example 14
Project: freemarker-scripting-master  File: PreparedParamsTest.java View source code
/**
     * PersistenceException will be thrown with cause of UnsupportedOperationException
     */
@Test(expected = PersistenceException.class)
public void testParamsObjectCall() {
    try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
        PreparedParamsMapper mapper = sqlSession.getMapper(PreparedParamsMapper.class);
        mapper.findUsingParamsObject(new PreparedParam());
    }
}
Example 15
Project: Mapper-master  File: TestInsert.java View source code
/**
     * 插入空数据,id不能为null,会报错
     */
@Test(expected = PersistenceException.class)
public void testDynamicInsertAll() {
    SqlSession sqlSession = MybatisHelper.getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        mapper.insert(new Country());
    } finally {
        sqlSession.close();
    }
}