org.springframework.jdbc.core.JdbcTemplate Java Examples

The following examples show how to use org.springframework.jdbc.core.JdbcTemplate. 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: MicroMetaDao.java    From nh-micro with Apache License 2.0 8 votes vote down vote up
public int insertMetaBeanById(String tableName, MicroMetaBean microMetaBean) {
	//JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder.getDbSource(dbName);
	JdbcTemplate jdbcTemplate =getMicroJdbcTemplate();
	final MicroMetaBean insertBean=microMetaBean;
	String timeName=getTimeName();
	String sql = "insert into " + tableName +"(id,meta_content,meta_key,meta_name,meta_type,remark,create_time,update_time) values(?,?,?,?,?,?,"+timeName+","+timeName+") ";
	List paramList=new ArrayList();
	paramList.add(insertBean.getId());
	paramList.add(insertBean.getMeta_content());
	paramList.add(insertBean.getMeta_key());
	paramList.add(insertBean.getMeta_name());
	paramList.add(insertBean.getMeta_type());
	paramList.add(insertBean.getRemark());
	logger.debug(sql);
	logger.debug(paramList.toArray());
	Integer retStatus=jdbcTemplate.update(sql,paramList.toArray());

	return retStatus;
}
 
Example #2
Source File: TaskLauncherSinkTests.java    From spring-cloud-task with Apache License 2.0 7 votes vote down vote up
@Before
public void setup() {
	this.properties = new HashMap<>();
	this.properties.put("spring.datasource.url", DATASOURCE_URL);
	this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME);
	this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD);
	this.properties.put("spring.datasource.driverClassName",
			DATASOURCE_DRIVER_CLASS_NAME);
	this.properties.put("spring.application.name", TASK_NAME);

	JdbcTemplate template = new JdbcTemplate(this.dataSource);
	template.execute("DROP ALL OBJECTS");

	DataSourceInitializer initializer = new DataSourceInitializer();

	initializer.setDataSource(this.dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.addScript(
			new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql"));
	initializer.setDatabasePopulator(databasePopulator);

	initializer.afterPropertiesSet();
}
 
Example #3
Source File: MicroMetaDao.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public List<Map<String, Object>> queryLimitObjJoinByCondition(String sql,int limit) {

		String tempType=calcuDbType();
		if(tempType!=null && tempType.equals("mysql")){
		//if(dbType!=null && dbType.equals("mysql")){
			sql=sql+" limit "+limit;
		}else{
			sql="select * from ("+sql+") where rownum <="+limit;
		}	
		JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
		logger.debug(sql);
		List<Map<String, Object>> retList0 = jdbcTemplate.queryForList(sql);
		//add 201807 ning
		//List<Map<String, Object>> retList=changeOutKeyCase4List(retList0);	
		
		//add 201902 ning
		List<Map<String, Object>> retList=ignoreKeyCase((List)retList0);
		
		return retList;
	}
 
Example #4
Source File: FlowPersistenceProviderMigrator.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    Options options = new Options();
    options.addOption("t", "to", true, "Providers xml to migrate to.");
    CommandLineParser parser = new DefaultParser();

    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        log.error("Unable to parse command line.", e);

        new HelpFormatter().printHelp("persistence-toolkit [args]", options);

        System.exit(PARSE_EXCEPTION);
    }

    NiFiRegistryProperties fromProperties = NiFiRegistry.initializeProperties(NiFiRegistry.getMasterKeyProvider());

    DataSource dataSource = new DataSourceFactory(fromProperties).getDataSource();
    DatabaseMetadataService fromMetadataService = new DatabaseMetadataService(new JdbcTemplate(dataSource));
    FlowPersistenceProvider fromPersistenceProvider = createFlowPersistenceProvider(fromProperties, dataSource);
    FlowPersistenceProvider toPersistenceProvider = createFlowPersistenceProvider(createToProperties(commandLine, fromProperties), dataSource);

    new FlowPersistenceProviderMigrator().doMigrate(fromMetadataService, fromPersistenceProvider, toPersistenceProvider);
}
 
Example #5
Source File: FullRecordApplier.java    From yugong with GNU General Public License v2.0 6 votes vote down vote up
protected void doApply(List<Record> records) {
    Map<List<String>, List<Record>> buckets = MigrateMap.makeComputingMap(new Function<List<String>, List<Record>>() {

        public List<Record> apply(List<String> names) {
            return Lists.newArrayList();
        }
    });

    // 根据目标库的不同,划分为多个bucket
    for (Record record : records) {
        buckets.get(Arrays.asList(record.getSchemaName(), record.getTableName())).add(record);
    }

    JdbcTemplate jdbcTemplate = new JdbcTemplate(context.getTargetDs());
    for (final List<Record> batchRecords : buckets.values()) {
        TableSqlUnit sqlUnit = getSqlUnit(batchRecords.get(0));
        if (context.isBatchApply()) {
            applierByBatch(jdbcTemplate, batchRecords, sqlUnit);
        } else {
            applyOneByOne(jdbcTemplate, batchRecords, sqlUnit);
        }
    }
}
 
Example #6
Source File: DbUtilities.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
public static final boolean dropSequenceIfExists(String sequenceName, final DataSource dataSource) {
	if(checkDbVendorIsOracle(dataSource)) {
		final JdbcTemplate template = new JdbcTemplate(dataSource);
		try {
	    	int foundSequences = template.queryForObject("SELECT COUNT(*) FROM all_sequences WHERE sequence_name = ?", Integer.class, sequenceName.toUpperCase());
	    	if (foundSequences > 0) {
	    		template.execute("DROP SEQUENCE " + sequenceName);
	    		return true;
	    	} else {
	    		return false;
	    	}
		} catch (Exception e) {
			return false;
		}
	} else {
		return false;
	}
}
 
Example #7
Source File: SpringBootDataCacheApplication.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public void printDataSourceInfo(JdbcTemplate jdbcTemplate) throws SQLException {

        DataSource dataSource = jdbcTemplate.getDataSource();

        Connection connection;
        if (dataSource != null) {
            connection = dataSource.getConnection();
        } else {
            log.error("获取 DataSource 失败");
            return;
        }

        if (connection != null) {
            log.info("DB URL: {}", connection.getMetaData().getURL());
        } else {
            log.error("获取 Connection 失败");
        }
    }
 
Example #8
Source File: SpringTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void spring_with_parent() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    BasicDataSource dataSource = getDataSource(false);

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("CREATE TABLE with_parent_1 (id INTEGER)");
    jdbcTemplate.execute("CREATE TABLE with_parent_2 (id INTEGER)");

    dataSource.close();
  }
  parent.finish();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size());

  checkSameTrace(spans);
  checkNoEmptyTags(spans);
}
 
Example #9
Source File: CogstackJobPartitioner.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
private ScheduledPartitionParams getDocmanParams(Timestamp jobStartTimeStamp, boolean inclusiveOfStart) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(sourceDataSource);
    String sql = MessageFormat.format("SELECT MAX({0}) AS max_id, MIN({0}) AS min_id, MAX({1}) AS max_time_stamp " +
                    ",MIN({1}) AS min_time_stamp FROM {2} ",
            column,timeStamp,table);

    Timestamp jobEndTimeStamp = getEndTimeStamp(jobStartTimeStamp);
    if(inclusiveOfStart) {
        sql = getDocmanStartTimeInclusiveSqlString(sql, jobStartTimeStamp, jobEndTimeStamp);
    }else if(!inclusiveOfStart){
        sql = getDocmanStartTimeExclusiveSqlString(sql, jobStartTimeStamp, jobEndTimeStamp);
    }else{
        throw new RuntimeException("cannot determine parameters");
    }
    logger.info ("This docman job SQL: " + sql);
    return (ScheduledPartitionParams) jdbcTemplate.queryForObject(
            sql, new PartitionParamsRowMapper());
}
 
Example #10
Source File: ThreadLocalDataSourceIndexTest.java    From tddl with Apache License 2.0 6 votes vote down vote up
@Test
public void test_不设i() {
    JdbcTemplate jt = new JdbcTemplate(createGroupDataSource("ds0:rw, ds1:r, ds2:r, ds3:r"));

    MockDataSource.clearTrace();
    GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(1);
    jt.query("select 1 from dual", new Object[] {}, new ColumnMapRowMapper());
    MockDataSource.showTrace();
    Assert.assertTrue(MockDataSource.hasTrace("", "ds1", "select 1 from dual"));

    MockDataSource.clearTrace();
    GroupDataSourceRouteHelper.executeByGroupDataSourceIndex(2);
    jt.query("select 1 from dual", new Object[] {}, new ColumnMapRowMapper());
    MockDataSource.showTrace();
    Assert.assertTrue(MockDataSource.hasTrace("", "ds2", "select 1 from dual"));
}
 
Example #11
Source File: JdbcConsumerAssociationStore.java    From openid4java with Apache License 2.0 6 votes vote down vote up
public void save ( String opUrl, Association association )
{
	cleanupExpired ( ) ;
	
	try
	{
		JdbcTemplate jdbcTemplate = getJdbcTemplate ( ) ;

		int cnt = jdbcTemplate.update ( _sqlInsert,
										new Object[]
											{
											 	opUrl,
												association.getHandle ( ),
												association.getType ( ),
												association.getMacKey ( ) == null ? null :
												    new String (
																Base64.encodeBase64 ( association.getMacKey ( ).getEncoded ( ) ) ),
												association.getExpiry ( ) } ) ;
	}
	catch ( Exception e )
	{
		_log.error ( "Error saving association to table: " + _tableName, e ) ;
	}
}
 
Example #12
Source File: EmployeeDAOJDBCTemplateImpl.java    From journaldev with MIT License 6 votes vote down vote up
@Override
public List<Employee> getAll() {
	String query = "select id, name, role from Employee";
	JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
	List<Employee> empList = new ArrayList<Employee>();

	List<Map<String,Object>> empRows = jdbcTemplate.queryForList(query);
	
	for(Map<String,Object> empRow : empRows){
		Employee emp = new Employee();
		emp.setId(Integer.parseInt(String.valueOf(empRow.get("id"))));
		emp.setName(String.valueOf(empRow.get("name")));
		emp.setRole(String.valueOf(empRow.get("role")));
		empList.add(emp);
	}
	return empList;
}
 
Example #13
Source File: DatabaseCreator.java    From infobip-spring-data-querydsl with Apache License 2.0 6 votes vote down vote up
DatabaseCreator(String url, String username, String password) {
    String databaseUrlPattern = getDatabaseUrlPattern(url);
    Pattern jdbcBaseUrlWithDbNamePattern = Pattern.compile(databaseUrlPattern);
    Matcher matcher = jdbcBaseUrlWithDbNamePattern.matcher(url);

    if (!matcher.matches()) {
        throw new IllegalArgumentException(url + " does not match " + databaseUrlPattern);
    }

    String jdbcBaseUrl = matcher.group("jdbcBaseUrl");
    String databaseName = matcher.group("databaseName");
    databaseExistsQuery = String.format("SELECT count(*) FROM sys.databases WHERE name='%s'", databaseName);
    createDatabaseQuery = String.format("CREATE DATABASE %s", databaseName);
    this.template = new JdbcTemplate(
            new SimpleDriverDataSource(getDriver(jdbcBaseUrl), jdbcBaseUrl, username, password));
}
 
Example #14
Source File: AccountingService.java    From EasyTransaction with Apache License 2.0 6 votes vote down vote up
@EtCps(cancelMethod="reverseEntry", idempotentType=BusinessProvider.IDENPOTENT_TYPE_FRAMEWORK,cfgClass=AccountingRequestCfg.class)
public AccountingResponse accounting(AccountingRequest param) {
	JdbcTemplate jdbcTemplate = getJdbcTemplate(param);
	
	TransactionId trxId = MetaDataFilter.getMetaData(EasytransConstant.CallHeadKeys.PARENT_TRX_ID_KEY);
	
	int update = jdbcTemplate.update("INSERT INTO `accounting` (`accounting_id`, `p_app_id`, `p_bus_code`, `p_trx_id`, `user_id`, `amount`, `create_time`) VALUES (NULL, ?, ?, ?, ?, ?, ?);",
			trxId.getAppId(),
			trxId.getBusCode(),
			trxId.getTrxId(),
			param.getUserId(),
			param.getAmount(),
			new Date());
	
	if(update != 1){
		throw new RuntimeException("unkonw Exception!");
	}
	return new AccountingResponse();
}
 
Example #15
Source File: EmbeddedDatabaseFactoryBeanTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testFactoryBeanLifecycle() throws Exception {
	EmbeddedDatabaseFactoryBean bean = new EmbeddedDatabaseFactoryBean();
	ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resource("db-schema.sql"),
		resource("db-test-data.sql"));
	bean.setDatabasePopulator(populator);
	bean.afterPropertiesSet();
	DataSource ds = bean.getObject();
	JdbcTemplate template = new JdbcTemplate(ds);
	assertEquals("Keith", template.queryForObject("select NAME from T_TEST", String.class));
	bean.destroy();
}
 
Example #16
Source File: RdbmsOperationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void parameterPropagation() {
	SqlOperation operation = new SqlOperation() {};
	DataSource ds = new DriverManagerDataSource();
	operation.setDataSource(ds);
	operation.setFetchSize(10);
	operation.setMaxRows(20);
	JdbcTemplate jt = operation.getJdbcTemplate();
	assertEquals(ds, jt.getDataSource());
	assertEquals(10, jt.getFetchSize());
	assertEquals(20, jt.getMaxRows());
}
 
Example #17
Source File: LoginDefaultHandler.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
public boolean isAdminUser(final PFUserDO user)
{
  final JdbcTemplate jdbc = new JdbcTemplate(dataSource);
  String sql = "select pk from t_group where name=?";
  final int adminGroupId = jdbc.queryForInt(sql, new Object[] { ProjectForgeGroup.ADMIN_GROUP.getKey()});
  sql = "select count(*) from t_group_user where group_id=? and user_id=?";
  final int count = jdbc.queryForInt(sql, new Object[] { adminGroupId, user.getId()});
  if (count != 1) {
    log.info("Admin login for maintenance (data-base update) failed for user '"
        + user.getUsername()
        + "' (user not member of admin group).");
    return false;
  }
  return true;
}
 
Example #18
Source File: MySQLTempStatTableCreator.java    From olat with Apache License 2.0 5 votes vote down vote up
/** set via spring **/
public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
    jdbcTemplate_ = jdbcTemplate;
    final DataSource dataSource = jdbcTemplate == null ? null : jdbcTemplate.getDataSource();
    Connection connection = null;
    try {
        if (dataSource != null) {
            connection = dataSource.getConnection();
        }
    } catch (final SQLException e) {
        log.warn("setJdbcTemplate: SQLException while trying to get connection for logging", e);
    }
    log.info("setJdbcTemplate: jdbcTemplate=" + jdbcTemplate + ", dataSource=" + dataSource + ", connection=" + connection);
}
 
Example #19
Source File: InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    new JdbcTemplate(dataSource).execute("CREATE TABLE COM_AUDIT_TRAIL ( "
            + "AUD_USER      VARCHAR(100)  NOT NULL, "
            + "AUD_CLIENT_IP VARCHAR(15)    NOT NULL, "
            + "AUD_SERVER_IP VARCHAR(15)    NOT NULL, "
            + "AUD_RESOURCE  VARCHAR(100)  NOT NULL, "
            + "AUD_ACTION    VARCHAR(100)  NOT NULL, "
            + "APPLIC_CD     VARCHAR(5)    NOT NULL, "
            + "AUD_DATE      TIMESTAMP      NOT NULL)");
}
 
Example #20
Source File: TaskStartTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
	this.properties = new HashMap<>();
	this.properties.put("spring.datasource.url", DATASOURCE_URL);
	this.properties.put("spring.datasource.username", DATASOURCE_USER_NAME);
	this.properties.put("spring.datasource.password", DATASOURCE_USER_PASSWORD);
	this.properties.put("spring.datasource.driverClassName",
			DATASOURCE_DRIVER_CLASS_NAME);
	this.properties.put("spring.application.name", TASK_NAME);
	this.properties.put("spring.cloud.task.initialize-enabled", "false");

	JdbcTemplate template = new JdbcTemplate(this.dataSource);
	template.execute("DROP TABLE IF EXISTS TASK_TASK_BATCH");
	template.execute("DROP TABLE IF EXISTS TASK_SEQ");
	template.execute("DROP TABLE IF EXISTS TASK_EXECUTION_PARAMS");
	template.execute("DROP TABLE IF EXISTS TASK_EXECUTION");
	template.execute("DROP TABLE IF EXISTS TASK_LOCK");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION_CONTEXT");
	template.execute("DROP TABLE IF EXISTS BATCH_STEP_EXECUTION");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_SEQ");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_PARAMS");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION_CONTEXT");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_EXECUTION");
	template.execute("DROP TABLE IF EXISTS BATCH_JOB_INSTANCE");
	template.execute("DROP SEQUENCE IF EXISTS TASK_SEQ");

	DataSourceInitializer initializer = new DataSourceInitializer();

	initializer.setDataSource(this.dataSource);
	ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
	databasePopulator.addScript(
			new ClassPathResource("/org/springframework/cloud/task/schema-h2.sql"));
	initializer.setDatabasePopulator(databasePopulator);
	initializer.afterPropertiesSet();
}
 
Example #21
Source File: FileConverter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Selects all the encrypted xml documents from krns_maint_doc_t, decrypts them, runs the rules to upgrade them,
 * encrypt them and update krns_maint_doc_t with the upgraded xml.
 *
 * @param settingsMap - the settings
 * @throws Exception
 */
public void runFileConversion(HashMap settingsMap, final String runMode, final String fromRange,
        final String toRange, final boolean hasRangeParameters) throws Exception {

    final EncryptionService encryptService = new EncryptionService((String) settingsMap.get("encryption.key"));

    String docSQL = "SELECT DOC_HDR_ID, DOC_CNTNT FROM krns_maint_doc_t ";

    // If user entered range add the sql parameters and filter results because DOC_HDR_ID is a varchar field.
    if (hasRangeParameters) {
        docSQL = docSQL.concat(" WHERE DOC_HDR_ID >= '" + fromRange + "' AND DOC_HDR_ID <= '" + toRange + "'");
    }
    System.out.println("SQL to run:"  + docSQL);

    jdbcTemplate = new JdbcTemplate(getDataSource(settingsMap));
    jdbcTemplate.query(docSQL, new RowCallbackHandler() {

        public void processRow(ResultSet rs) throws SQLException {
            // Check that all docId's is in range
            if (hasRangeParameters) {
                int docId = Integer.parseInt(rs.getString(1));
                if (docId >= Integer.parseInt(fromRange) && docId <= Integer.parseInt(toRange)) {
                    processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
                }
            } else {
                processDocumentRow(rs.getString(1), rs.getString(2), encryptService, runMode);
            }
        }
    });

    System.out.println(totalDocs + " maintenance documents upgraded.");

}
 
Example #22
Source File: DatabaseScriptLifecycleHandler.java    From vladmihalcea.wordpress.com with Apache License 2.0 5 votes vote down vote up
public DatabaseScriptLifecycleHandler(DataSource dataSource,
                                      Resource[] initScripts,
                                      Resource[] destroyScripts) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);
    this.initScripts = initScripts;
    this.destroyScripts = destroyScripts;
}
 
Example #23
Source File: DatabaseUpdateDaoTest.java    From projectforge-webapp with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void createAndDropTable()
{
  logon(ADMIN);
  final Table table = new Table("t_test") //
  .addAttribute(new TableAttribute("name", TableAttributeType.VARCHAR, 5).setPrimaryKey(true))//
  .addAttribute(new TableAttribute("counter", TableAttributeType.INT)) //
  .addAttribute(new TableAttribute("money", TableAttributeType.DECIMAL, 8, 2).setNullable(false)) //
  .addAttribute(new TableAttribute("address_fk", TableAttributeType.INT).setForeignTable("t_address").setForeignAttribute("pk"));
  final StringBuffer buf = new StringBuffer();
  final MyDatabaseUpdateDao databaseUpdateDao = myDatabaseUpdater.getDatabaseUpdateDao();
  databaseUpdateDao.buildCreateTableStatement(buf, table);
  assertEquals("CREATE TABLE t_test (\n" //
      + "  name VARCHAR(5),\n" //
      + "  counter INT,\n" //
      + "  money DECIMAL(8, 2) NOT NULL,\n" //
      + "  address_fk INT,\n" //
      + "  PRIMARY KEY (name),\n" //
      + "  FOREIGN KEY (address_fk) REFERENCES t_address(pk)\n" //
      + ");\n", buf.toString());
  assertTrue(databaseUpdateDao.createTable(table));
  assertTrue(databaseUpdateDao.doesTableExist("t_test"));
  assertTrue(databaseUpdateDao.dropTable("t_test"));
  assertTrue(databaseUpdateDao.dropTable("t_test"));
  assertTrue(databaseUpdateDao.createTable(table));
  final JdbcTemplate jdbc = new JdbcTemplate(dataSource);
  jdbc.execute("INSERT INTO t_test (name, counter, money) VALUES('test', 5, 5.12);");
  assertFalse("Data base is not empty!", databaseUpdateDao.dropTable("t_test"));
  jdbc.execute("DELETE FROM t_test;");
}
 
Example #24
Source File: JobCommandTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void tearDown() {
	JdbcTemplate template = new JdbcTemplate(applicationContext.getBean(DataSource.class));
	template.afterPropertiesSet();
	final String TASK_EXECUTION_FORMAT = "DELETE FROM task_execution WHERE task_execution_id = %d";
	final String TASK_BATCH_FORMAT = "DELETE FROM task_task_batch WHERE task_execution_id = %d";

	for (Long id : taskExecutionIds) {
		template.execute(String.format(TASK_BATCH_FORMAT, id));
		template.execute(String.format(TASK_EXECUTION_FORMAT, id));
	}
}
 
Example #25
Source File: NamedParameterJdbcTemplateTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testBatchUpdateWithEmptyMap() throws Exception {
	@SuppressWarnings("unchecked")
	final Map<String, Integer>[] ids = new Map[0];
	namedParameterTemplate = new NamedParameterJdbcTemplate(new JdbcTemplate(dataSource, false));

	int[] actualRowsAffected = namedParameterTemplate.batchUpdate(
			"UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = :id", ids);
	assertTrue("executed 0 updates", actualRowsAffected.length == 0);
}
 
Example #26
Source File: DocOperateImpl.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public int removeDoc(String productName, String version, String component, String locale,
		JdbcTemplate jdbcTemplate) {
	// TODO Auto-generated method stub
	String delSql = "delete from vip_msg v where v.product = ? and v.version = ? and v.component= ? and v.locale = ?";
	logger.debug(((DruidDataSource) (jdbcTemplate.getDataSource())).getName());
	logger.debug(delSql);
	logger.debug(String.join(", ", productName, version, component, locale));
	return jdbcTemplate.update(delSql, productName, version, component, locale);
}
 
Example #27
Source File: HibernateValidationRuleStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public HibernateValidationRuleStore( SessionFactory sessionFactory, JdbcTemplate jdbcTemplate,
    ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService,
    PeriodService periodService )
{
    super( sessionFactory, jdbcTemplate, publisher, ValidationRule.class, currentUserService, aclService, true );

    checkNotNull( periodService );

    this.periodService = periodService;
}
 
Example #28
Source File: JdbcTemplateDelegated.java    From qconfig with MIT License 5 votes vote down vote up
public <T> T queryForObject(String sql, Class<T> requiredType, Object... args) throws DataAccessException {
    T result = null;
    for (JdbcTemplate jdbcTemplate : jdbcTemplates.values()) {
        result = jdbcTemplate.queryForObject(sql, requiredType, args);
        if (result != null) {
            break;
        }
    }

    return result;
}
 
Example #29
Source File: DataBaseTransactionLogWritterImpl.java    From EasyTransaction with Apache License 2.0 5 votes vote down vote up
@Override
public void appendTransLog(final String appId, final String busCode, final long trxId,
		final List<Content> newOrderedContent, final boolean finished) {
	
	transactionTemplate.execute(new TransactionCallback<Object>(){
		@Override
		public Object doInTransaction(TransactionStatus status) {
			JdbcTemplate localJdbcTemplate = getJdbcTemplate();
			
			//unfinished tag
			byte[] transIdByteForm = idCodec.getTransIdByte(new TransactionId(appId, busCode, trxId));
			localJdbcTemplate.update(insertUnfinished, transIdByteForm,new Date());
			
			if(newOrderedContent != null && newOrderedContent.size() != 0){
				//concrete log
				int logUpdateConut = localJdbcTemplate.update(insertTransDetail,
						transIdByteForm,
						objectSerializer.serialization(newOrderedContent),
						new Date()
						);
				if(logUpdateConut != 1){
					throw new RuntimeException("write log error!");
				}
				
				if(LOG.isDebugEnabled()){
					LOG.debug(newOrderedContent.toString());
				}
			}
			
			if(finished){
				//remove unfinished tag
				localJdbcTemplate.update(deleteUnfinishedTag, transIdByteForm);
			}
			
			return null;
		}
		
	});
}
 
Example #30
Source File: MicroMetaDao.java    From nh-micro with Apache License 2.0 5 votes vote down vote up
public List<MicroMetaBean> queryMetaBeanByCondition(String tableName, String condition,Object[] paramArray,int[] typeArray) {
	List<MicroMetaBean> retBeanList=new ArrayList();
	/*		JdbcTemplate jdbcTemplate = (JdbcTemplate) MicroDbHolder
	.getDbSource(dbName);*/
	JdbcTemplate jdbcTemplate = getMicroJdbcTemplate();
	String sql = "select * from " + tableName + " where "+condition;
	logger.debug(sql);
	logger.debug(Arrays.toString(paramArray));
	List<Map<String, Object>> retList = jdbcTemplate.queryForList(sql,paramArray,typeArray);
	if(retList==null){
		return retBeanList;
	}
	
	for(Map<String,Object> rowMap:retList){
		MicroMetaBean metaBean = new MicroMetaBean();
		metaBean.setId((String) rowMap.get("id"));
		metaBean.setMeta_content((String) rowMap.get("meta_content"));
		metaBean.setMeta_key((String) rowMap.get("meta_key"));
		metaBean.setMeta_name((String) rowMap.get("meta_name"));
		metaBean.setMeta_type((String) rowMap.get("meta_type"));
		metaBean.setRemark((String) rowMap.get("remark"));
		metaBean.setCreate_time((Date) rowMap.get("create_time"));
		metaBean.setUpdate_time((Date) rowMap.get("update_time"));
		retBeanList.add(metaBean);
	}
	return retBeanList;
}