@Test public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { job = new JobSupport("test-job"); job.setRestartable(true); job.setName("spam"); JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); cacheJobIds(execution); execution.setEndTime(new Timestamp(System.currentTimeMillis())); repository.update(execution); execution.setStatus(BatchStatus.FAILED); int before = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(1, before); long t0 = System.currentTimeMillis(); try { doConcurrentStart(); fail("Expected JobExecutionAlreadyRunningException"); } catch (JobExecutionAlreadyRunningException e) { // expected } long t1 = System.currentTimeMillis(); int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertNotNull(execution.getId()); assertEquals(before, after); logger.info( "Duration: " + (t1 - t0) + " - the second transaction did not block if this number is less than about 1000."); }
@Transactional @Test public void testFindOrCreateJobConcurrently() throws Exception { job.setName("bar"); int before = 0; assertEquals(0, before); long t0 = System.currentTimeMillis(); try { doConcurrentStart(); fail("Expected JobExecutionAlreadyRunningException"); } catch (JobExecutionAlreadyRunningException e) { // expected } long t1 = System.currentTimeMillis(); JobExecution execution = (JobExecution) list.get(0); assertNotNull(execution); int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertNotNull(execution.getId()); assertEquals(before + 1, after); logger.info( "Duration: " + (t1 - t0) + " - the second transaction did not block if this number is less than about 1000."); }
public int countResult(CspQueryTo queryTo) { SimpleJdbcTemplate sjt = getSimpleJdbcTemplate(); String sql = "select count(*) from PIDB_CSP where 1=1 "; String sqlWhere = generateWhereCause(queryTo); sql = sql + sqlWhere; logger.debug(sql); return sjt.queryForInt(sql, new Object[] {}); }
@Transactional @Test public void testFindOrCreateJob() throws Exception { job.setName("foo"); int before = 0; JobExecution execution = repository.createJobExecution(job.getName(), new JobParameters()); int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(before + 1, after); assertNotNull(execution.getId()); }
/** * 编辑操作(增删改查都可以) * * @param sql * @param obj * @return */ public int getForInt(String sql, Object... obj) { int index = 0; try { index = simpleJdbcTemplate.queryForInt(sql, obj); } catch (DataAccessException e) { log.info(e); return 0; // throw new DaoException("数据库操作失败!",e); } return index; }
public Employee getTotalSalaryForManager(Employee employee) { int total = simpleJdbcTemplate.queryForInt(QUERY_ALL_SALARIES, new Object[] {employee.getEmpId()}); logger.info( "getTotalSalaryForManager for employee id " + employee.getEmpId() + " returned " + total); employee.setTotal(total); return employee; }
public int countResult(ProjectQueryTo queryTo) { SimpleJdbcTemplate sjt = getSimpleJdbcTemplate(); String sql = "select count(*) from pidb_project p left join pidb_project_code pc on p.proj_name=pc.proj_name where 1 = 1 "; if (queryTo.getReleaseTo() != null && !queryTo.getReleaseTo().equals("")) { if (queryTo.getReleaseTo().equals("HX") || queryTo.getReleaseTo().equals("WP")) { sql += " AND (pc.RELEASE_TO ='" + queryTo.getReleaseTo() + "'" + " or pc.RELEASE_TO ='ALL')"; } } String whereCause = generateWhereCause(queryTo); sql += whereCause; return sjt.queryForInt(sql, new Object[] {}); }
/** * Method 'insert' * * @param dto * @return PoPk */ public PoPk insert(Po dto) { SqlUpdate su = new SqlUpdate( dataSource, "INSERT INTO " + getTableName() + " ( ponumber, podate, prsnumber, prsdate, deliverydate, poreferensi, createdby, corpid, wh_code, department_name, supplier_name, currency, prsremarks, role_code,status, status_date,status, status_date_date ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.compile(); su.update( new Object[] { dto.getPonumber(), dto.getPodate(), dto.getPrsnumber(), dto.getPrsdate(), dto.getDeliverydate(), dto.getPoreferensi(), dto.getCreatedby(), dto.getCorpid(), dto.getWhCode(), dto.getDepartmentName(), dto.getSupplierName(), dto.getCurrency(), dto.getPrsremarks(), dto.getRoleCode(), dto.getStatus(), dto.getStatusdate() }); PoPk pk = new PoPk(); pk.setId(jdbcTemplate.queryForInt("select @@IDENTITY")); return pk; }
@AfterTransaction public void onTearDownAfterTransaction() throws Exception { for (Long id : jobExecutionIds) { simpleJdbcTemplate.update( "DELETE FROM BATCH_JOB_EXECUTION_CONTEXT where JOB_EXECUTION_ID=?", id); simpleJdbcTemplate.update("DELETE FROM BATCH_JOB_EXECUTION where JOB_EXECUTION_ID=?", id); } for (Long id : jobIds) { simpleJdbcTemplate.update("DELETE FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", id); } for (Long id : jobIds) { int count = simpleJdbcTemplate.queryForInt( "SELECT COUNT(*) FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", id); assertEquals(0, count); } }
/** * Method 'insert' * * @param dto * @return StockInPk */ public StockInPk insert(StockIn dto) { SqlUpdate su = new SqlUpdate( dataSource, "INSERT INTO " + getTableName() + " ( document_no, document_date, product_code, product_name, quantity, is_active, is_delete, created_by, created_date, updated_by, updated_date ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.INTEGER)); su.declareParameter(new SqlParameter(java.sql.Types.CHAR)); su.declareParameter(new SqlParameter(java.sql.Types.CHAR)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.declareParameter(new SqlParameter(java.sql.Types.VARCHAR)); su.declareParameter(new SqlParameter(java.sql.Types.TIMESTAMP)); su.compile(); su.update( new Object[] { dto.getDocumentNo(), dto.getDocumentDate(), dto.getProductCode(), dto.getProductName(), dto.getQuantity(), dto.getIsActive(), dto.getIsDelete(), dto.getCreatedBy(), dto.getCreatedDate(), dto.getUpdatedBy(), dto.getUpdatedDate() }); StockInPk pk = new StockInPk(); pk.setId(jdbcTemplate.queryForInt("select @@IDENTITY")); return pk; }
/* * Message processing is successful on the second attempt but must receive * the message again. */ @Test public void testExternalRetrySuccessOnSecondAttempt() throws Exception { assertInitialState(); final ItemWriter<Object> writer = new ItemWriter<Object>() { public void write(final List<? extends Object> texts) { for (Object text : texts) { simpleJdbcTemplate.update( "INSERT into T_BARS (id,name,foo_date) values (?,?,null)", list.size(), text); if (list.size() == 1) { throw new RuntimeException("Rollback!"); } } } }; try { new TransactionTemplate(transactionManager) .execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { final Object item = provider.read(); RetryCallback<Object> callback = new RetryCallback<Object>() { public Object doWithRetry(RetryContext context) throws Exception { writer.write(Collections.singletonList(item)); return null; } }; return retryTemplate.execute(callback, new DefaultRetryState(item)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } }); fail("Expected Exception"); } catch (Exception e) { assertEquals("Rollback!", e.getMessage()); // Client of retry template has to take care of rollback. This would // be a message listener container in the MDP case. } new TransactionTemplate(transactionManager) .execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { final String item = provider.read(); RetryCallback<Object> callback = new RetryCallback<Object>() { public Object doWithRetry(RetryContext context) throws Exception { writer.write(Collections.singletonList(item)); return null; } }; return retryTemplate.execute(callback, new DefaultRetryState(item)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } }); List<String> msgs = getMessages(); // The database portion committed once... int count = simpleJdbcTemplate.queryForInt("select count(*) from T_BARS"); assertEquals(1, count); // ... and so did the message session. assertEquals("[]", msgs.toString()); }
private void assertInitialState() { int count = simpleJdbcTemplate.queryForInt("select count(*) from T_BARS"); assertEquals(0, count); }
/* * Message processing fails on both attempts. */ @Test public void testExternalRetryWithRecovery() throws Exception { assertInitialState(); final String item = provider.read(); final RetryCallback<String> callback = new RetryCallback<String>() { public String doWithRetry(RetryContext context) throws Exception { simpleJdbcTemplate.update( "INSERT into T_BARS (id,name,foo_date) values (?,?,null)", list.size(), item); throw new RuntimeException("Rollback!"); } }; final RecoveryCallback<String> recoveryCallback = new RecoveryCallback<String>() { public String recover(RetryContext context) { recovered.add(item); return item; } }; String result = "start"; for (int i = 0; i < 4; i++) { try { result = (String) new TransactionTemplate(transactionManager) .execute( new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { try { return retryTemplate.execute( callback, recoveryCallback, new DefaultRetryState(item)); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } }); } catch (Exception e) { if (i < 3) assertEquals("Rollback!", e.getMessage()); // Client of retry template has to take care of rollback. This // would // be a message listener container in the MDP case. } } // Last attempt should return last item. assertEquals("foo", result); List<String> msgs = getMessages(); assertEquals(1, recovered.size()); // The database portion committed once... int count = simpleJdbcTemplate.queryForInt("select count(*) from T_BARS"); assertEquals(0, count); // ... and so did the message session. assertEquals("[]", msgs.toString()); }
public boolean checkUser(final long userId, final String passwd) { return 0 < jdbcTemplate.queryForInt( "select count(*) from auth_user where user_id = ? and passwd_hash = ?", userId, passwd); }