org.apache.ibatis.exceptions.PersistenceException Java Examples

The following examples show how to use org.apache.ibatis.exceptions.PersistenceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AttachmentHandler.java    From taskana with Apache License 2.0 6 votes vote down vote up
void insertNewAttachmentOnTaskUpdate(TaskImpl newTaskImpl, Attachment attachment)
    throws AttachmentPersistenceException {
  LOGGER.debug("entry to insertNewAttachmentOnTaskUpdate()");
  AttachmentImpl attachmentImpl = (AttachmentImpl) attachment;
  initAttachment(attachmentImpl, newTaskImpl);

  try {
    attachmentMapper.insert(attachmentImpl);
    LOGGER.debug(
        "TaskService.updateTask() for TaskId={} INSERTED an Attachment={}.",
        newTaskImpl.getId(),
        attachmentImpl);
  } catch (PersistenceException e) {
    throw new AttachmentPersistenceException(
        String.format(
            "Cannot insert the Attachement %s for Task %s  because it already exists.",
            attachmentImpl.getId(), newTaskImpl.getId()),
        e.getCause());
  }
  LOGGER.debug("exit from insertNewAttachmentOnTaskUpdate(), returning");
}
 
Example #2
Source File: BasicDao.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
private BasicModel _findById(String id, int time)
{
    if (time > 10)
    {
        System.out.println("查询到 BasicModel 对象失败次数>10,放弃查询");
        return null;
    }

    try
    {
        return (BasicModel) session.selectOne(className + ".findById", id);
    } catch (PersistenceException exception)
    {
        System.out.println("没有查询到 BasicModel 对象,继续查询");
        return _findById(id, ++time);
    }
}
 
Example #3
Source File: ConcurrentEngineUsageTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
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) {
    log.debug("Retrying process start FAILED " + MAX_RETRIES + " times");
  }
}
 
Example #4
Source File: NestedResultHandlerTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test(expected=PersistenceException.class)
public void testUnorderedGetPersonWithHandler() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    sqlSession.select("getPersonsWithItemsOrdered", new ResultHandler() {
      public void handleResult(ResultContext context) {
        Person person = (Person) context.getResultObject();
        if ("grandma".equals(person.getName())) {
          Assert.assertEquals(2, person.getItems().size());
        }
      }
    });
  } finally {
    sqlSession.close();
  }
}
 
Example #5
Source File: ConcurrentEngineUsageTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
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) {
    log.debug("Retrying process start FAILED " + MAX_RETRIES + " times");
  }
}
 
Example #6
Source File: ConcurrentEngineUsageTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
protected void retryFinishTask(String taskId) {
  int retries = MAX_RETRIES;
  int timeout = 200;
  boolean success = false;
  while (retries > 0 && !success) {
    try {
      taskService.complete(taskId);
      success = true;
    } catch (PersistenceException pe) {
      retries = retries - 1;
      log.debug("Retrying task completion - " + (MAX_RETRIES - retries));
      try {
        Thread.sleep(timeout);
      } catch (InterruptedException ignore) {
      }
      timeout = timeout + 200;
    }
  }

  if (!success) {
    log.debug("Retrying task completion FAILED " + MAX_RETRIES + " times");
  }
}
 
Example #7
Source File: Main.java    From ClosureTableCateogryStore with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	Utils.disableIllegalAccessWarning();
	if (args.length != 3) {
		System.err.println("请设置数据库连接参数,例如:");
		System.err.println("\tjava -jar closure-table.jar jdbc:mariadb://localhost:3306/test root password");
		return;
	}

	try {
		session = Utils.createSqlSession("org.mariadb.jdbc.Driver", args[0], args[1], args[2]);
		CategoryMapper mapper = session.getMapper(CategoryMapper.class);
		repository = new Repository(mapper);
		Category.categoryMapper = mapper; // 如果使用Spring,可以用@Configurable来注入此依赖。
		Utils.executeScript(session.getConnection(), "table.sql");

		Runtime.getRuntime().addShutdownHook(new Thread(() -> {
			Utils.dropTables(session.getConnection());
		}));
		runDemo();
	} catch (PersistenceException e) {
		System.out.println("错误:无法连接数据库,请检查启动参数。");
	}
}
 
Example #8
Source File: CustomSqlSessionTemplate.java    From ApplicationPower with Apache License 2.0 6 votes vote down vote up
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    final SqlSession sqlSession = getSqlSession(CustomSqlSessionTemplate.this.getSqlSessionFactory(), CustomSqlSessionTemplate.this.executorType, CustomSqlSessionTemplate.this.exceptionTranslator);
    try {
        Object result = method.invoke(sqlSession, args);
        if (!isSqlSessionTransactional(sqlSession, CustomSqlSessionTemplate.this.getSqlSessionFactory())) {
            // 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 (CustomSqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
            Throwable translated = CustomSqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
            if (translated != null) {
                unwrapped = translated;
            }
        }
        throw unwrapped;
    } finally {
        closeSqlSession(sqlSession, CustomSqlSessionTemplate.this.getSqlSessionFactory());
    }
}
 
Example #9
Source File: SmallIntArrayTest.java    From mmpt with MIT License 6 votes vote down vote up
@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 #10
Source File: CFExceptionMapperTest.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
public static Stream<Arguments> testHandleException() {
    return Stream.of(
    // @formatter:off
        Arguments.of(new NotFoundException("Not found"), new RestResponse(404, "Not found")),
        Arguments.of(new ConflictException("Already exists"), new RestResponse(409, "Already exists")),
        Arguments.of(new ParsingException("Bad request"), new RestResponse(400, "Bad request")),
        Arguments.of(new ContentException("Bad request"), new RestResponse(400, "Bad request")),
        Arguments.of(new SLException("SL exception"), new RestResponse(500, "SL exception")),
        Arguments.of(new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found"), new RestResponse(404, "Not found")),
        Arguments.of(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Bad request"), new RestResponse(400, "Bad request")),
        Arguments.of(new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Something went wrong"), new RestResponse(500, "Something went wrong")),
        Arguments.of(new CloudOperationException(HttpStatus.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase(), "Rate limit exceeded"), new RestResponse(502, "429 Too Many Requests: Rate limit exceeded")),
        Arguments.of(new SQLException(), new RestResponse(500, Messages.TEMPORARY_PROBLEM_WITH_PERSISTENCE_LAYER)),
        Arguments.of(new PersistenceException(), new RestResponse(500, Messages.TEMPORARY_PROBLEM_WITH_PERSISTENCE_LAYER))
    // @formatter:on
    );
}
 
Example #11
Source File: LoggerDAO.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void storeData(IFallback object) throws IDBPersistenceException {
  SqlSession session = null;
  try {
    session = sqlSessionFactory.openSession();
    LoggerMapper<T> loggerMapper = session.getMapper(mapperInterface);
    loggerMapper.insertLog((T) object);
    session.commit();
  } catch (PersistenceException ex1) {
    String message = "Exception caught while persisting an object to the history";
    LOGGER.error(message, ex1);
    if (session != null)
      session.rollback();
    throw new IDBPersistenceException(message, ex1);
  } finally {
    if (session != null)
      session.close();
  }
}
 
Example #12
Source File: BatchPersistenceManagerImpl.java    From c2mon with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Will not shutdown correctly until all elements can be persisted.
 */
@Override
public synchronized void stop() {
  LOGGER.info("Shutting down cache persistence manager (" + cache.getClass().getSimpleName() + ")");
  started = false;
  cachePersistenceThreadPoolTaskExecutor.shutdown();
  //may be none-empty if added using addElementToPersist
  while (!toBePersisted.isEmpty()) {
    LOGGER.debug("Detected cache objects that need persisting... trying to persist them.");
    toBePersistedLock.writeLock().lock();
    try {
      cachePersistenceDAO.persistBatch(new ArrayList<>(toBePersisted));
      toBePersisted.clear();
    } catch (PersistenceException e) {
      LOGGER.error("Exception caught while persisting final batch of cache objects - will try again in 1s", e);
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e1) {
        LOGGER.error("Interrupted during sleep", e1);
      }
    } finally {
      toBePersistedLock.writeLock().unlock();
    }
  }
}
 
Example #13
Source File: ConcurrentEngineUsageTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void retryFinishTask(String taskId) {
    int retries = MAX_RETRIES;
    int timeout = 200;
    boolean success = false;
    while (retries > 0 && !success) {
        try {
            taskService.complete(taskId);
            success = true;
        } catch (PersistenceException pe) {
            retries = retries - 1;
            LOGGER.debug("Retrying task completion - {}", (MAX_RETRIES - retries));
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ignore) {
            }
            timeout = timeout + 200;
        }
    }

    if (!success) {
        LOGGER.debug("Retrying task completion FAILED {} times", MAX_RETRIES);
    }
}
 
Example #14
Source File: ConcurrentEngineUsageTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
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;
            LOGGER.debug("Retrying process start - {}", (MAX_RETRIES - retries));
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ignore) {
            }
            timeout = timeout + 200;
        }
    }
    if (!success) {
        LOGGER.debug("Retrying process start FAILED {} times", MAX_RETRIES);
    }
}
 
Example #15
Source File: ConcurrentEngineUsageTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
protected void retryFinishTask(String taskId) {
    int retries = MAX_RETRIES;
    int timeout = 200;
    boolean success = false;
    while (retries > 0 && !success) {
        try {
            taskService.complete(taskId);
            success = true;
        } catch (PersistenceException pe) {
            retries = retries - 1;
            LOGGER.debug("Retrying task completion - {}", (MAX_RETRIES - retries));
            try {
                Thread.sleep(timeout);
            } catch (InterruptedException ignore) {
            }
            timeout = timeout + 200;
        }
    }

    if (!success) {
        LOGGER.debug("Retrying task completion FAILED {} times", MAX_RETRIES);
    }
}
 
Example #16
Source File: TenancyTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeDeploymentIdWithClash() {
    String processDefinitionIdWithTenant = deployTestProcessWithTestTenant("tenantA");
    deployOneTaskTestProcess();
    String deploymentId = this.repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionIdWithTenant).singleResult()
            .getDeploymentId();

    // Changing the one with tenant now back to one without should clash,
    // cause there already exists one
    assertThatThrownBy(() -> repositoryService.changeDeploymentTenantId(deploymentId, ""))
            .isInstanceOf(PersistenceException.class);

    // Deploying another version should just up the version
    String processDefinitionIdNoTenant2 = deployOneTaskTestProcess();
    assertThat(repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionIdNoTenant2).singleResult().getVersion()).isEqualTo(2);

}
 
Example #17
Source File: NestedResultHandlerTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test(expected=PersistenceException.class)
public void testUnorderedGetPersonWithHandler() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    sqlSession.select("getPersonsWithItemsOrdered", new ResultHandler() {
      public void handleResult(ResultContext context) {
        Person person = (Person) context.getResultObject();
        if ("grandma".equals(person.getName())) {
          Assert.assertEquals(2, person.getItems().size());
        }
      }
    });
  } finally {
    sqlSession.close();
  }
}
 
Example #18
Source File: UnknownObjectTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldFailBecauseThereIsAPropertyWithoutTypeHandler() throws Exception {
  // create a SqlSessionFactory
  Reader reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/unknownobject/mybatis-config.xml");
  sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
  reader.close();

  // populate in-memory database
  SqlSession session = sqlSessionFactory.openSession();
  Connection conn = session.getConnection();
  reader = Resources.getResourceAsReader("org/apache/ibatis/submitted/unknownobject/CreateDB.sql");
  ScriptRunner runner = new ScriptRunner(conn);
  runner.setLogWriter(null);
  runner.runScript(reader);
  reader.close();
  session.close();
}
 
Example #19
Source File: SqlSessionManagerTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfMappedStatementDoesNotExistAndSqlSessionIsOpen() throws Exception {
  try {
    manager.startManagedSession();
    manager.selectList("ThisStatementDoesNotExist");
    fail("Expected exception to be thrown due to statement that does not exist.");
  } catch (PersistenceException e) {
    assertTrue(e.getMessage().contains("does not contain value for ThisStatementDoesNotExist"));
  } finally {
    manager.close();
  }
}
 
Example #20
Source File: SelectKeyTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void testSeleckKeyReturnsTooManyData() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Map<String, String> parms = new HashMap<String, String>();
    parms.put("name", "Fred");
    sqlSession.insert("org.apache.ibatis.submitted.selectkey.Table2.insertTooManyValuesInSelectKey", parms);
    sqlSession.insert("org.apache.ibatis.submitted.selectkey.Table2.insertTooManyValuesInSelectKey", parms);
  } finally {
    sqlSession.close();
  }
}
 
Example #21
Source File: NonExistentVariablesTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected = PersistenceException.class)
public void testWrongParameter() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    mapper.count(1, "John");
    fail("should have failed");
  } finally {
    sqlSession.close();
  }
}
 
Example #22
Source File: RefidResolutionTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected = PersistenceException.class)
public void testIncludes() throws Exception {
  String resource = "org/apache/ibatis/submitted/refid_resolution/MapperConfig.xml";
  Reader reader = Resources.getResourceAsReader(resource);
  SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
  SqlSessionFactory sqlSessionFactory = builder.build(reader);
  sqlSessionFactory.getConfiguration().getMappedStatementNames();
}
 
Example #23
Source File: SelectKeyTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected = PersistenceException.class)
public void testSeleckKeyWithWrongKeyProperty() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Name name = new Name();
    name.setName("Kyoto");
    sqlSession.insert("org.apache.ibatis.submitted.selectkey.Table2.insertWrongKeyProperty", name);
  } finally {
    sqlSession.close();
  }
}
 
Example #24
Source File: SafeDeleteByFieldTest.java    From Mapper with MIT License 5 votes vote down vote up
@Test(expected = PersistenceException.class)
public void testSafeDeleteNull() {
    SqlSession sqlSession = getSqlSession();
    try {
        CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
        mapper.delete(null);
    } finally {
        sqlSession.close();
    }
}
 
Example #25
Source File: UUIDTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldGetAUser() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    User user = mapper.getUser(UUID.fromString("38400000-8cf0-11bd-b23e-10b96e4ef00d"));
    Assert.assertEquals("User1", user.getName());
  } finally {
    sqlSession.close();
  }
}
 
Example #26
Source File: ImmutablePOJOTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldFailLoadingImmutablePOJO() {
  final SqlSession session = factory.openSession();
  try {
    final ImmutablePOJOMapper mapper = session.getMapper(ImmutablePOJOMapper.class);
    mapper.getImmutablePOJONoMatchingConstructor(POJO_ID);
  } finally {
    session.close();
  }
}
 
Example #27
Source File: ValueInMapTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldWorkWithAList() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    List<String> list = new ArrayList<String>();
    list.add("users");
    Integer count = sqlSession.selectOne("count2",list);
    Assert.assertEquals(new Integer(1), count);
  } finally {
    sqlSession.close();
  }
}
 
Example #28
Source File: MapTypeHandlerTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldGetAUserFromXML() {
  SqlSession sqlSession = sqlSessionFactory.openSession();
  try {
    Mapper mapper = sqlSession.getMapper(Mapper.class);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("id", 1);
    params.put("name", "User1");
    User user = mapper.getUserXML(params);
    Assert.assertEquals("User1", user.getName());
  } finally {
    sqlSession.close();
  }
}
 
Example #29
Source File: ImmutablePOJOTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test(expected=PersistenceException.class)
public void shouldFailLoadingImmutablePOJO() {
  final SqlSession session = factory.openSession();
  try {
    final ImmutablePOJOMapper mapper = session.getMapper(ImmutablePOJOMapper.class);
    mapper.getImmutablePOJONoMatchingConstructor(POJO_ID);
  } finally {
    session.close();
  }
}
 
Example #30
Source File: SelectKeyTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@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();
  }
}